How to save information to a log file in Python
About formats, a little bit about journaling and a Python code example
Suppose you need to save some information about an event and when it happened to a log file. One of the most appropriate file formats for this is JSON.
What is JSON
An example of where this format is used very extensively is in web service responses. In the “old” days, web services used XML as the primary format for transferring data, but since JSON came along (the JSON format is defined in RFC 4627 by Douglas Crockford), it has become the preferred format because it is much lighter.
Here’s an example function to save information to a log in Python. We will call it at the time of an event, and it will save all the necessary information to the log.
First, we need to open the log file in order to add information to it. We will use the log file augment mode and for this we will use the checkbox “a” - append.
Then we record information about the event in the log:
This will create a nicely formatted log file:
I hope this helps you.