How to Quickly Log into A File with Python
The aim of this page📝 is to define steps for a quick setup of the Python logging mechanism — for further discussion dive into the constantly awesome Real Python and its Logging in Python
1. DEFAULTS
- start with
import logging
- the most recognizable/typical feature for the language of logging are 5 severity levels
1. DEBUG
2. INFO
3. WARNING
4. ERROR
5. CRITICAL
- by default, the logging module logs the messages with a severity level of WARNING or above
- logger is the feature that does the writing and — importantly — it can/should have a custom name (not here)
- the default logger is called
root
- the default syntax for the call is
<!-- DEFAULT CALL SYNTAX/EXAMPLE -->
logging.<SEVERITY LEVEL>('<MESSAGE>')
logging.critical('Server DOWN')
<!-- DEFAULT LOG SYNTAX/EXAMPLE -->
<SEVERITY>:<LOGGER>:<MESSAGE>
CRITICAL:root:Server DOWN
2. DEFINE
- since we are not using custom logger — use the
basicConfig(**kwargs)
- if confused with
**kwargs
, read Use **kwargs To Accept An Arbitrary Number Of Keyword Arguments in Python | by Pavol Kutaj | Feb, 2022 | Medium - 5 parameters are commonly passed into the
basicConfig
method
- In my case I am setting up the
basicConfig
in a dedicated module as follows
2.1. FORMAT DETAILS
format
parameter listed above can take a string with logrecord-attributes < logging < Logging facility for Python- I am using this format
<!-- FORMAT ATTRIBUTES DEFINED -->
format='%(asctime)s | %(levelname)s | %(message)s'
<!-- LOG EXAMPLE -->
2022-03-10 14:53:37 | INFO | Create: New Doc...
3. CALL
- You call the defined logger when/where/as many times as you need it
- The utilization of f-strings — introduced in Python 3.6 — is optimal for message formatting
- I import the module with
from logger import logging
and call it as follows with the default call syntax
logging.<SEVERITY LEVEL>('<MESSAGE>')
- My example including the import of a dedicated
logger
module (used across my app)
kb.log
is populated with something like
2022-03-05 08:24:31 | INFO | Create: New Doc | 01.01 test-ignore | pavol kutaj | ZD URL not available
4. SHUTDOWN
- After the logging is done include
logging.shutdown()
- I need this because I am logging locally and I push logs to a GitHub repo during the execution.
- Without that, the file handler is opened and git does not detect the change to logs
Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call. When the logging module is imported, it registers this function as an exit handler (see atexit), so normally there’s no need to do that manually.
— from https://docs.python.org/3/library/logging.html#logging.shutdown