Python logging package usage summary, pythonlogging
1. Introduction to logging
The logging package of Python provides a general log system for third-party modules or applications. This module provides different log levels and records logs in different ways, such as files, http get/POST, SMTP, and Socket. You can even implement specific logging methods by yourself.
The logging package defines important classes such as Logger, Formatter, Handler, and Filter, in addition to the config module.
Logger is a log object and provides APIs for logging operations.
Formatter defines the log record format and content
Handler defines the log writing destination. You can save the log to the local file, write a log file every hour, and upload the log to another machine through socket. Python provides more than a dozen practical handler types, including StreamHandler, BaseRotatingHandler, SocketHandler, DatagramHandler, and SMTPHandler. We can use the addHandler () method of the Logger object to output logs to multiple destinations.
2. Logging package
Logging package is introduced in python programming. Therefore, a Logging object named root and many other names can exist. Handler and Formatter of different Logger objects are set separately.
(1) logging. getLogger () If getLogging does not contain a parameter, the Logger object named root is returned. If a parameter is included, the Logger object named root is used. The Logger object with the same name is the same.
(2) logging. basicConfig () This method is used to configure a Logger object named root.
(3) logging.info () logging. debug () and so on, use the root Logger object for information output. If you use other Logging objects for log output, you can use Logging. getLogger (name). info.
(4) Log Level
CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0
In python, there are six levels of values 0, 10, 20, 30, 40, and 50. These six levels correspond to a String constant respectively as the level name, as shown above. However, you can use the logging. addLevelName (20, "NOTICE:") method to change the ing relationship and customize the Log Level name.
By using the setLevel () method of the Logger object, you can configure the default log Level of the Logging object. Only when the level of a log is greater than or equal to the default level will it be output to the log file.
When logging.info (msg) is used to output logs, the number 20 is used as the log level value in the internal encapsulation. By default, 20 corresponds to INFO, but if addLevelName () is used () after the level name corresponding to 20 is modified, the printed log will be the personalized level name.
3. Use the configuration file for the logging package
In 1 ~ As described in 2, Handler and Formatter of a Logger object are defined or bound in the program. In fact, the personalized configuration of Logging can be stored in the configuration file.
An example of the logging configuration file is as follows:
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=
The corresponding program is:
Import logging. config logging. config. fileConfig ("logging. conf ") # Use the configuration file # create logger = logging. getLogger ("simpleExample") # "application" code logger. debug ("debug message") logger.info ("info message") logger. warn ("warn message") logger. error ("error message") logger. critical ("critical message ")
4. A common Logging encapsulation Tool
#! /Usr/bin/env python #-*-coding: UTF-8-*-# coding = UTF-8 import logging import OS class Logger (object ): "encapsulated Logger tool" def _ init _ (self, logPath): "initial" log_path = logPath logging. addLevelName (20, "NOTICE:") logging. addLevelName (30, "WARNING:") logging. addLevelName (40, "FATAL:") logging. addLevelName (50, "FATAL:") logging. basicConfig (level = logging. DEBUG, format = "% (levelname) s % (asctime) s [pid: % (process) s] % (filename) s % (message) s ", datefmt = "% Y-% m-% d % H: % M: % S", filename = log_path, filemode = "a") console = logging. streamHandler () console. setLevel (logging. DEBUG) formatter = logging. formatter ("% (levelname) s [pid: % (process) s] % (message) s") console. setFormatter (formatter) logging. getLogger (""). addHandler (console) def debug (self, msg = ""): "output DEBUG level LOG" logging. debug (str (msg) def info (self, msg = ""): "output INFO level LOG" logging.info (str (msg) def warning (self, msg = ""): "output WARN level LOG" "logging. warning (str (msg) def exception (self, msg = ""): "output Exception stack LOG" logging. exception (str (msg) def error (self, msg = ""): "output ERROR level LOG" logging. error (str (msg) def critical (self, msg = ""): "output FATAL level LOG" logging. critical (str (msg) if _ name _ = "_ main _": testlog = Logger ("oupput. log ") testlog.info (" info .... ") testlog. warning ("warning .... ") testlog. critical ("critical .... ") try: lists = [] print lists [1] failed t Exception as ex:" logging. exception () Output Format: FATAL: [pid: 7776] execute task failed. the exception as follows: Traceback (most recent call last): File "logtool. py ", line 86, in <module> print lists [1] IndexError: list index out of range" "testlog. exception ("execute task failed. the exception as follows :") testlog.info ("++ ++ ") "logging. error () Output Format: FATAL: [pid: 7776] execute task failed. the exception as follows: "" testlog. error ("execute task failed. the exception as follows: ") exit (1)
Note: The exception () method can print the stack information of the exception completely. The error () method only prints the information passed in by the parameter.
Note:
According to the official documents, logging is thread-safe. That is to say, it is safe to write logs to the same file simultaneously by multiple threads in a process. However, it is insecure for multiple processes to write logs to the same file.