Output log in JSON format with Python standard logging

How to use logging

First of all, the basics. Write the log on the library side and Decide how to handle the log on the client side.

Library side

First, add the following 4 lines to the beginning of each file

from logging import getLogger, DEBUG, NullHandler
logger = getLogger(__name__)
logger.addHandler(NullHandler())
logger.setLevel(DEBUG)

This will output to logger with .debug, .info, etc.

logger.info("Enter special block")

Since NullHandler is registered, this log will be discarded if the client does not capture it.

Client side

The name of the logger on the library side is registered with __name__. For example, it is registered with a name such as mod.submod1, mod.submod2. Since it is layered with ., you can receive the logs of both submodules by referencing it with mod. If no name is given, all logs will be collected.

--Output all logs to standard error output (sys.stderr)

import logging
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

--Output the log of INFO or higher of mod module to a file (mod.log)

import logging
logger = logging.getLogger("mod")
logger.addHandler(logging.FileHandler("mod.log", mode="w"))
logger.setLevel(logging.INFO)

Of course, it is possible to prepare a function on the library side that makes it easy for the client to execute these codes.

Output in JSON

Considering the subsequent analysis, I want a structured log. Actually, you can give a dictionary object such as logger.info:

logger.info({
  "key": value,
  "homhom": 0,
})

If you do not set it in particular, the result of printing this normally will be output, so it looks the same as JSON, but It's not official JSON, so it's hard to parse it. That's where python jsonlogger comes in. This will be reformatted as JSON when output on the client side.

To output to the above file:

import logging
from pythonjsonlogger import jsonlogger
h = logging.FileHandler("mod.log", mode="w")
h.setFormatter(jsonlogger.JsonFormatter())
logging.getLogger("mod").addHandler(h)

This will output a valid JSON log for each row. So log

with open("mod.log") as f:
    df = pd.DataFrame([json.loads(l) for l in f])

You can easily pour it into pandas like this.

Recommended Posts

Output log in JSON format with Python standard logging
Easily format JSON in Python
Format json with Vim (with python)
Get standard output in real time with Python subprocess
Read json file with Python, format it, and output json
Make standard output non-blocking in Python
Unit test log output with python
Python logging standard library for file output by log level
Easy with just Python! Output Graphviz figures in draw.io format!
Try logging in to qiita with Python
Data input / output in Python (CSV, JSON)
Output Python log to console with GAE
Best practice for logging in JSON format on AWS Lambda / Python
UnicodeEncodeError struggle with standard output of python3
format in python
[python3] Implement debug log output function easily with logging and Click
Read JSON with Python and output as CSV
Python log is not output with docker-compose up
Log in to Yahoo Business with Selenium Python
How to output "Ketsumaimo" as standard output in Python
[CentOS8] How to output Python standard output to systemd log
[Python] Use JSON with Python
Image format in Python
Japanese output in Python
Get the result in dict format with Python psycopg2
Pretty print json or yaml with color in python
Convert / return class object to JSON format in Python
Find this week's date in any format with python
Japanese output when dealing with python in visual studio
Scraping with selenium in Python
Scraping with chromedriver in python
POST json with Python3 script
Debugging with pdb in Python
Try Python output with Haxe 3.2
Test standard output with Pytest
Working with sounds in Python
Scraping with Selenium in Python
Output large log with discord.py
Scraping with Tor in Python
Transposed matrix in Python standard
Tweet with image in Python
Thorough logging strategy in Python
Combined with permutations in Python
String format with Python% operator
Read Fortran output in python
Read json data with python
How to output a document in pdf format with Sphinx
Change the standard output destination to a file in Python
[For beginners] Summary of standard input in Python (with explanation)
[Selenium] Change log output destination when executing phantomjs in python3
[GCP] How to output Cloud Functions log to Cloud Logging (Stackdriver Logging) (Python)
How to log in to AtCoder with Python and submit automatically
Number recognition in images with Python
Convert to a string while outputting standard output with Python subprocess
Export DB data in json format
How to not escape Japanese when dealing with json in python
Testing with random numbers in Python
Matrix representation with Python standard input
Output 2017 Premium Friday list in Python
[Python] logging in your own module
GOTO in Python with Sublime Text 3