Python's log module logging and syslog

Source: Internet
Author: User
Tags openlog syslog

The Syslog module is a module that works in a UNIX environment and is not available for Windows, and can be used with the logging module in a Windows environment.

 First, syslog

The Syslog module can be used to record information about the operation of the system, which is provided by a syslog (Priority,message), which feeds a message into the system log, and the default option for priority is Log_info,openlog ([ Ident[,logoption[,facility]]), which is used to open the log, ident will be added to each log, Logoption is the log option, facility is an optional tool parameter. Closelog () is used to close the log.

The order of priority priorities from high to low is: Log_emerg, Log_alert, Log_crit, Log_err, log_warning, Log_notice,log_info, Log_debug,

By default, it is Log_info.

Syslog logging options are log_cons,log_ndelay,log_nowait,log_pid,log_perror.

The options for facility are LOG_AUTH,LOG_CRON,LOG_DAEMON,LOG_KERN,LOG_LOCALX,LOG_MAIL,LOG_NEWS,LOG_USER,LOG_UUCP.

#!/usr/bin/env pythonImportSyslog,sys,ossys.openlog (): Syslog.openlog ("%s[%d]") %(Os.path.basename (Sys.argv[0],os.getpid ()), 0,syslog. Log_daemon) Syslog.syslog ("stared")Try:    Raiseruntimeerror,e:except: Type,exception,trace=sys.exc_info () Excclass=str (Exception.__class__) Message=Str (Exception) Syslog.syslog (syslog. ERROR,"%s:%s"% (Excclass,message))
Openlog,syslog These two functions and combined with the syslog.conf configuration, you can customize a very good logging function. Through the Openlog function, we can classify the information into what file and take the Syslog function parameters to what kind of service level can be recorded to what kind of file, the premise needs to syslog.conf the match. Below I will use popular language and examples to illustrate the following functions: Syslog.openlog (ident[, logopt[, facility]) This is the function that initializes the Syslog interface, where there is a required parameter and two optional parameters. The first parameter, ident, is an identity string, which is the name of the program in each line of the log, such as: Syslog.openlog ("test.py") Syslog.syslog ("The process is test.py") Tail-n 1/ VAR/LOG/MESSAGESAPR 16:26:52 databak test.py:The process is test.py right? You got it, don't you? Second parameter, logopt option name: Log_cons,log_ndelay,log_nowait,log_pid,log_perror You can select one or more (to use or operator "|"), such as: Syslog.openlog ("test.py", syslog.) Log_pid|syslog. Log_perror) Syslog.syslog ("The messages print PID and messages print to stderr") >>> Syslog.syslog ("the messages P Rint PID and messages print to stderr ") test.py[16826]: The messages print PID and messages print to stderr This function, you understand? Next, we look at the Syslog function in the above example, the Syslog function has been accompanied by us, I believe that we have seen a bit of the doorway, and now I still put the function of publicity to everyone. Syslog.syslog ([ Priority], messageThere are two parameters, an optional one must write. The message is needless to say, I have all the examples, just to illustrate the optional parameters. Priority, Name: Log_emerg,log_alert,log_crit,log_err,log_warning,log_info,log_debug (default = Log_info) We want to write the authentication error information to the Python.err file, then modify the Syslog.confauth.err/var/log/python.err See program: Syslog . Openlog ("test.py", syslog. Log_pid,syslog. Log_auth) Syslog.syslog (Syslog. Log_err, "Add error information to python.err file") Second, logging1. Simply print the log to the screen

import logging

logging.debug(‘This is debug message‘)
logging.info(‘This is info message‘)
logging.warning(‘This is warning message‘)

屏幕上打印:
WARNING:root:This is warning message

By default, logging prints the log to the screen with a log level of warning;
Log level size relationships are: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself.

2. Configure the output format and mode of the log by Logging.basicconfig function

import logging

logging.basicConfig(level=logging.DEBUG,
                format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,
                datefmt=‘%a, %d %b %Y %H:%M:%S‘,
                filename=‘myapp.log‘,
                filemode=‘w‘)
    
logging.debug(‘This is debug message‘)
logging.info(‘This is info message‘)
logging.warning(‘This is warning message‘)

./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

Parameters of the Logging.basicconfig function:
FileName: Specify the log file name
FileMode: Same as file function, specify open mode of log file, ' W ' or ' a '
Format: Specifies the formats and contents of the output, format can output a lot of useful information, as in the example above:
% (Levelno) S: Print the value of the log level
% (levelname) S: Print log level name
% (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]
% (filename) s: Prints the current name of the executing program
% (funcName) s: Print the current function of the log
% (Lineno) d: Print the current line number of the log
% (asctime) s: Time to print logs
% (thread) d: Print thread ID
% (threadname) s: Print thread name
% (process) d: Print process ID
% (message) s: Print log information
DATEFMT: Specify time format, same as Time.strftime ()
Level: Sets the log levels by default to logging. WARNING
Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously

3. Output logs to both file and screen at the same time

Import logging

Logging.basicconfig (level=logging. DEBUG,
format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',
Datefmt= '%a,%d%b%Y%h:%m:%s ',
Filename= ' Myapp.log ',
Filemode= ' W ')

#################################################################################################
#定义一个StreamHandler, print Info-level or higher log information to a standard error and add it to the current log-processing object #
console = logging. Streamhandler ()
Console.setlevel (Logging.info)
Formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ')
Console.setformatter (Formatter)
Logging.getlogger ("). AddHandler (console)
#################################################################################################

Logging.debug (' This is Debug message ')
Logging.info (' This is Info message ')
Logging.warning (' This is warning message ')

屏幕上打印:
root        : INFO     This is info message
root        : WARNING  This is warning message

./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging Log Rollback

import logging
from logging.handlers import RotatingFileHandler

#################################################################################################
#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
Rthandler = RotatingFileHandler(‘myapp.log‘, maxBytes=10*1024*1024,backupCount=5)
Rthandler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(name)-12s: %(levelname)-8s %(message)s‘)
Rthandler.setFormatter(formatter)
logging.getLogger(‘‘).addHandler(Rthandler)
################################################################################################

As can be seen from the above example and in this example, logging has a main object of log processing, and other processing methods are added through AddHandler.
Several handle methods of logging are as follows:

Logging. Streamhandler: Log output to stream, can be sys.stderr, sys.stdout, or file
Logging. Filehandler: Log output to File

Log rollback method, using Rotatingfilehandler and Timedrotatingfilehandler when actually used
Logging.handlers.BaseRotatingHandler
Logging.handlers.RotatingFileHandler
Logging.handlers.TimedRotatingFileHandler

Logging.handlers.SocketHandler: Remote output log to TCP/IP sockets
Logging.handlers.DatagramHandler: Remote output log to UDP sockets
Logging.handlers.SMTPHandler: Remote output log to e-mail address
Logging.handlers.SysLogHandler: Log Output to Syslog
Logging.handlers.NTEventLogHandler: Remote output log to Windows NT/2000/XP event log
Logging.handlers.MemoryHandler: Log output to in-memory development buffer
Logging.handlers.HTTPHandler: Remote output to HTTP server via "GET" or "POST"

Because Streamhandler and filehandler are common log processing methods, they are included directly in the logging module, while others are included in the Logging.handlers module.
Please refer to the python2.5 manual for the use of the other processing methods described above.

5. Configuring logs via the Logging.config module

#logger.conf

###############################################

[loggers]
keys=root,example01,example02

[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################

[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=(‘myapp.log‘, ‘a‘)

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=(‘myapp.log‘, ‘a‘, 10*1024*1024, 5)

###############################################

[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=

In Example 3:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug(‘This is debug message‘)
logger.info(‘This is info message‘)
logger.warning(‘This is warning message‘)

In Example 4:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")

logger.debug(‘This is debug message‘)
logger.info(‘This is info message‘)
logger.warning(‘This is warning message‘)

6.logging is thread-safe

Python's log module logging and syslog

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.