Class for generating log messages for different actions. All methods must return a dictionary listing the parameters ``level``, ``msg`` and ``args`` which are going to be used for constructing the log message when calling ``logging.log``. Dictionary keys for the method outputs:
| 35 | |
| 36 | |
| 37 | class LogFormatter: |
| 38 | """Class for generating log messages for different actions. |
| 39 | |
| 40 | All methods must return a dictionary listing the parameters ``level``, ``msg`` |
| 41 | and ``args`` which are going to be used for constructing the log message when |
| 42 | calling ``logging.log``. |
| 43 | |
| 44 | Dictionary keys for the method outputs: |
| 45 | |
| 46 | * ``level`` is the log level for that action, you can use those from the |
| 47 | `python logging library <https://docs.python.org/3/library/logging.html>`_ : |
| 48 | ``logging.DEBUG``, ``logging.INFO``, ``logging.WARNING``, ``logging.ERROR`` |
| 49 | and ``logging.CRITICAL``. |
| 50 | * ``msg`` should be a string that can contain different formatting placeholders. |
| 51 | This string, formatted with the provided ``args``, is going to be the long message |
| 52 | for that action. |
| 53 | * ``args`` should be a tuple or dict with the formatting placeholders for ``msg``. |
| 54 | The final log message is computed as ``msg % args``. |
| 55 | |
| 56 | Users can define their own ``LogFormatter`` class if they want to customize how |
| 57 | each action is logged or if they want to omit it entirely. In order to omit |
| 58 | logging an action the method must return ``None``. |
| 59 | |
| 60 | Here is an example on how to create a custom log formatter to lower the severity level of |
| 61 | the log message when an item is dropped from the pipeline:: |
| 62 | |
| 63 | class PoliteLogFormatter(logformatter.LogFormatter): |
| 64 | def dropped(self, item, exception, response, spider): |
| 65 | return { |
| 66 | 'level': logging.INFO, # lowering the level from logging.WARNING |
| 67 | 'msg': "Dropped: %(exception)s" + os.linesep + "%(item)s", |
| 68 | 'args': { |
| 69 | 'exception': exception, |
| 70 | 'item': item, |
| 71 | } |
| 72 | } |
| 73 | """ |
| 74 | |
| 75 | def crawled( |
| 76 | self, request: Request, response: Response, spider: Spider |
| 77 | ) -> LogFormatterResult: |
| 78 | """Logs a message when the crawler finds a webpage.""" |
| 79 | request_flags = f" {request.flags!s}" if request.flags else "" |
| 80 | response_flags = f" {response.flags!s}" if response.flags else "" |
| 81 | return { |
| 82 | "level": logging.DEBUG, |
| 83 | "msg": CRAWLEDMSG, |
| 84 | "args": { |
| 85 | "status": response.status, |
| 86 | "request": request, |
| 87 | "request_flags": request_flags, |
| 88 | "referer": referer_str(request), |
| 89 | "response_flags": response_flags, |
| 90 | # backward compatibility with Scrapy logformatter below 1.4 version |
| 91 | "flags": response_flags, |
| 92 | }, |
| 93 | } |
| 94 |