Formatting the Output
While you can pass any variable that can be represented as a string from your program as a message to your logs, there are some basic elements that are already a part of the LogRecord
and can be easily added to the output format. If you want to log the process ID along with the level and message, you can do something like this:
import logging
logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This is a Warning')
Here’s what you’ll get:
18472-WARNING-This is a Warning
00:00
You can pass any variable you want to the config function’s format
parameter, but there are some built-in variables that are a part of the LogRecord
that you can log as well. We’ll talk more about the LogRecord
later, but basically it’s just all the metadata that’s associated with a certain event.
00:19 Some examples of this data are the process ID, the level name, and the message. If we run this program, you’ll see that we get the process ID, the severity level, and the message name written to the console and separated by dashes.
00:37
Here’s another example, this time adding time and date info. asctime
adds the time of creation of the LogRecord
. And so as you can see, we get both the date and the time in our log output along with the message.
00:53
But we can also use the datefmt
parameter to specify how the date and time should be formatted. This is a little bit easier to read than the output we saw earlier, and it’s customizable, so we can change it on a need-by-need basis.
Become a Member to join the conversation.