The built-in log module in Python logging usage _python

Source: Internet
Author: User
Tags current time log4j in python

Logging Module Introduction

Python's logging module provides a common logging system that can be easily used by Third-party modules or applications. This module provides different log levels and can record logs in different ways, such as files, HTTP get/post,smtp,socket, etc., and can even implement specific logging methods for itself.
The logging module is the same as the log4j mechanism, but the specific implementation details are different. module provides logger,handler,filter,formatter.

    • Logger: Provides log interface for use in code. There are two types of logger operations: Configuring and sending log messages. The Logger object can be obtained by Logging.getlogger (name), and the root object is returned if name is not specified, and the same logger object is returned multiple times using the same name call GetLogger method.
    • Handler: Sends the log record to the appropriate destination (destination), such as file, socket, etc. A Logger object can add 0 to multiple handler through the AddHandler method, and each handler can define different log levels to achieve a log-rating filter display.
    • Filter: Provides an elegant way to determine whether a log record is sent to handler.
    • Formatter: Specifies the specific format of the logging output. The formatter construction method requires two parameters: the format string of the message and the date string, both of which are optional.

Like log4j, Logger,handler and log message calls can have specific log levels (levels), only at a level larger than the logger and handler levels of the log message.

Logging usage Analysis

1. Initialize logger = Logging.getlogger ("Endlesscode"), preferably after the GetLogger () method plus the name of the module to be logged, and% (name) s in the following log format corresponds to the module name here
2. Set level Logger.setlevel (logging. Debug), logging has NotSet < DEBUG < INFO < WARNING < ERROR < critical these levels, log will record set level above the log
3. Handler, commonly used in Streamhandler and filehandler,windows you can simply understand that one is a console and a file log, a print on a CMD window, a record on a file
4. Formatter, which defines the order, structure and content of the final log information, I like to use this format ' [% (asctime) s] [% (levelname) s]% (message) s ', '%y-%m-%d%h:%m:%s ',
% (name) s Logger's name
% (levelname) s text in the form of log level
% (message) s user output messages
% (asctime) s string in the form of the current time. The default format is "2003-07-08 16:49:45,896". The comma is followed by a millisecond
% (Levelno) s digital form of log level
% (pathname) s The full pathname of the module that calls the log output function, may not have
% (filename) s The file name of the module that calls the log output function
% (module) s calls the module name of the log output function
% (funcName) s call Function name for log output function
% (Lineno) d The line of code where the statement of the log output function is called
% (created) F current time, represented by floating-point numbers of the UNIX standard representation time
% (relativecreated) d output log information, the number of milliseconds since logger was created
% (thread) d thread ID. May not have
% (threadname) s thread name. May not have
% (process) d process ID. May not have
5. Record using Object.debug (message) to log
Below to write an example, in the CMD window only the error level above the log, but in the log more than debug information

Import logging
logger = Logging.getlogger ("simple_example")
logger.setlevel (logging. Debug)
# Create a filehandler to record the log in the file, level is debug above
fh = logging. Filehandler ("Spam.log")
fh.setlevel (logging. DEBUG)
# Create a streamhandler to put the log on the cmd window, the level is above the error
ch = logging. Streamhandler ()
ch.setlevel (logging. ERROR)
# set log format
formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s")
Ch.setformatter (Formatter)
Fh.setformatter (Formatter)
#将相应的handler添加在logger对象中
logger.addhandler (CH)
Logger.addhandler (FH)
# Start Logging logger.debug (' Debug message ')
logger.info (' info message ')
Logger.warn ("Warn message")
logger.error ("error message")
logger.critical ("Critical Message")

When you run it, you'll see that the cmd window only records two, and five logs are logged in the Spam.log.

When a project is larger, log is used in different files, and you can consider encapsulating it as a class to use

#! /usr/bin/env python #coding =gbk import Logging,os class Logger:def __init__ (self, path,clevel = logging. Debug,flevel = logging. DEBUG): Self.logger = Logging.getlogger (path) self.logger.setLevel (logging. DEBUG) FMT = logging. Formatter (' [% (asctime) s] [% (levelname) s]% (message) s ', '%y-%m-%d%h:%m:%s ') #设置CMD日志 sh = logging. Streamhandler () sh.setformatter (FMT) sh.setlevel (clevel) #设置文件日志 fh = logging.

 Filehandler (Path) fh.setformatter (FMT) fh.setlevel (flevel) self.logger.addHandler (SH) self.logger.addHandler (FH) def debug (self,message): Self.logger.debug (message) def info (self,message): Self.logger.info (Message) def War (Sel
  F,message): Self.logger.warn (message) def error (Self,message): Self.logger.error (message) def CRI (self,message): Self.logger.critical (message) if __name__ = = ' __main__ ': Logyyx = Logger (' Yyx.log ', logging. Error,logging. Debug) Logyyx.debug (' One Debug Information ') Logyyx.info (' one info info ') Logyyx.war (' One Warning information ') logyyx.error (' AError information ') LOGYYX.CRI (' A fatal critical message ')

 

So whenever you use it, just instantiate an object.

Logobj = Logger (' filename ', clevel,flevel)

If you want to in the CMD window for error log red, warning log yellow, then you can use the cTYPES module

#! /usr/bin/env python #coding =gbk import logging,os import ctypes foreground_white = 0x0007 foreground_blue = 0x01 # text C
Olor contains blue.
foreground_green= 0x02 # text color contains GREEN.
foreground_red = 0x04 # text color contains RED. Foreground_yellow = foreground_red | Foreground_green std_output_handle= -11 std_out_handle = Ctypes.windll.kernel32.GetStdHandle (std_output_handle) def Set_color (color, handle=std_out_handle): bool = Ctypes.windll.kernel32.SetConsoleTextAttribute (handle, color) return BOOL Class Logger:def __init__ (self, path,clevel = logging. Debug,flevel = logging. DEBUG): Self.logger = Logging.getlogger (path) self.logger.setLevel (logging. DEBUG) FMT = logging. Formatter (' [% (asctime) s] [% (levelname) s]% (message) s ', '%y-%m-%d%h:%m:%s ') #设置CMD日志 sh = logging. Streamhandler () sh.setformatter (FMT) sh.setlevel (clevel) #设置文件日志 fh = logging. Filehandler (Path) fh.setformatter (FMT) fh.setlevel (flevel) self.logger.addHandler (SH) self.logger. AddHandler (FH) def debug (self,message): Self.logger.debug (message) def info (self,message): Self.logger.info (Messa GE) def War (Self,message,color=foreground_yellow): Set_color (color) self.logger.warn (message) Set_color (foreground _white def error (self,message,color=foreground_red): Set_color (color) self.logger.error (message) Set_color (Foregr Ound_white def CRI (self,message): self.logger.critical (message) If __name__ = ' __main__ ': Logyyx = Logger (' Yyx.log ' , logging. Warning,logging. Debug) Logyyx.debug (' One Debug Information ') Logyyx.info (' one info info ') Logyyx.war (' One Warning information ') logyyx.error (' One Error information ') Logyyx
 . CRI (' A fatal critical message ')

Multi-module using logging
the logging module guarantees that multiple calls to Logging.getlogger (' Log_name ') in the same Python interpreter will return the same logger instance, even in the case of multiple modules. So the typical way to use logging in a multiple-module scenario is to configure logging in the main module, which will be used for multiple sub modules, and then get logger objects directly through GetLogger in other modules.
Configuration file:

[Loggers] 
Keys=root,main 
 
[handlers] 
keys=consolehandler,filehandler 
 
[formatters] 
keys=fmt 
 
[logger_ Root] 
level=debug 
handlers=consolehandler 
 
[Logger_main] 
level=debug 
qualname=main 
Handlers=filehandler 
 
[Handler_consolehandler] 
class=streamhandler 
level=debug 
formatter= FMT 
args= (sys.stdout,) 
 
[Handler_filehandler] 
Class=logging.handlers.rotatingfilehandler 
Level=debug 
formatter=fmt 
args= (' Tst.log ', ' a ', 20000,5,) 
 
[formatter_fmt] 
format=% (asctime) s -% (name) s-% (levelname) s-% (message) s 
datefmt= 

Main module main.py:

Import Logging 
import logging.config 
 
logging.config.fileConfig (' logging.conf ') 
Root_logger = Logging.getlogger (' root ') 
root_logger.debug (' Test root logger ... ') 
 
logger = Logging.getlogger (' main ') 
Logger.info (' Test main logger ') 
logger.info (' Start import module \ mod\ ' ... ') 
import mod 
 
logger.debug (' Let\ ' s test mod.testlogger () ') 
Mod.testlogger () 
 
root_logger.info (' Finish test ... ') 

Sub-module mod.py:

Import Logging 
Import submod 
 
logger = Logging.getlogger (' main.mod ') 
logger.info (' Logger of mod say Something ... ') 
 
def testlogger (): 
  logger.debug (' This is Mod.testlogger ... ') 
  submod.tst () 

Double module submod.py:

Import logging 
 
logger = Logging.getlogger (' main.mod.submod ') 
logger.info (' Logger of submod say ... ') 
 
def TST (): 
  logger.info (' This is submod.tst () ... ') 

Then run the Python main.py, console output:

2012-03-09 18:22:22,793-root-debug-test Root Logger 
... 2012-03-09 18:22:22,793-main-info-test Main logger 
2012-03-09 18:22:22,809-main-info-start Import module ' MoD ' ... 
2012-03-09 18:22:22,809-main.mod.submod-info-logger of Submod say something ... 
2012-03-09 18:22:22,809-main.mod-info-logger say something ... 
2012-03-09 18:22:22,809-main-debug-let ' s Test mod.testlogger () 
2012-03-09 18:22:22,825-main.mod-debug-thi S is Mod.testlogger 
... 2012-03-09 18:22:22,825-main.mod.submod-info-this is submod.tst () 
... 2012-03-09 18:22:22,841-root-info-finish Test ... 

You can see, as expected, and then look at the destinations of the output in the Tst.log,logger configuration:

2012-03-09 18:22:22,793-main-info-test Main logger 
2012-03-09 18:22:22,809-main-info-start Import module ' MoD ' ... 
2012-03-09 18:22:22,809-main.mod.submod-info-logger of Submod say something ... 
2012-03-09 18:22:22,809-main.mod-info-logger say something ... 
2012-03-09 18:22:22,809-main-debug-let ' s Test mod.testlogger () 
2012-03-09 18:22:22,825-main.mod-debug-this Is Mod.testlogger 
... 2012-03-09 18:22:22,825-main.mod.submod-info-this is submod.tst () ... 

There is no information from the root logger output in Tst.log because only main logger and its child logger are configured to use Rotatingfilehandler in logging.conf, and root logger is output to standard output.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.