The new version of Python logging encapsulation supports simultaneous output to the console, file, and Socket

Source: Internet
Author: User

The logging encapsulation of python is updated. Currently, it supports outputting data to the console, file, and socket at the same time. At the same time, you can clear all the handler of the root logger When configuring config_logging or config_logging_plus, avoid repeated output in some cases.
DetailsCodeAs follows:

 #  -*-Coding: UTF-8 -*-  '''  Modified on 2012-11-27 @ Summary: Clear old root logger handlers when reconfig logging @ Author: jerrykwancreated on @ Summary: logging config @ Author: jerrykwan  '''  Import  Logging  Import  Logging. handlers  Import OS  Import  Syslevels = { '  Noset  '  : Logging. notset,  '  Debug  '  : Logging. debug,  '  Info  '  : Logging. info,  ' Warning  '  : Logging. Warning,  '  Error  '  : Logging. error,  '  Critical  '  : Logging. Critical}  #  Set up logging to file  #  Logging. basicconfig (Level = logging. notset,  # Format = "% (asctime) S % (name)-12 S % (levelname)-8 S % (Message) S"  #  )  #  # Filename = "./log.txt ",  #  # Filemode = "W ")  #  Create logs file folder  Def Config_logging (file_name = "  Log.txt  " , Log_level ="  Noset  "  ):  '''  @ Summary: config logging to write logs to local file @ Param file_name: name of Log File @ Param log_level: Log Level  '''  Logs_dir = OS. Path. Join (OS. Path. dirname ( _ File __ ), "  Logs  "  )  If OS. Path. exists (logs_dir)And  OS. Path. isdir (logs_dir ):  Pass      Else  : OS. makedirs (logs_dir)  #  Clear old root logger handlers Logging. getlogger ( "" ). Handlers = [] File_name = OS. Path. Join (logs_dir, file_name)  #  Define a rotating file Handler Rotatingfilehandler = logging. Handlers. rotatingfilehandler (filename =File_name, maxbytes = 1024*1024*50 , Backupcount = 5 ) Formatter = Logging. formatter ( "  % (Asctime) S % (name)-12 S % (levelname)-8 S % (Message) S  "  ) Rotatingfilehandler. setformatter (formatter) logging. getlogger (  ""  ). Addhandler (rotatingfilehandler)  # Define a handler whitch writes messages to sys Console = Logging. streamhandler ()  #  Set a format which is simple for console use Formatter = logging. formatter ( "  % (Name)-12 s: % (levelname)-8 S % (Message) S  "  )  #  Tell the handler to use this format  Console. setformatter (formatter)  # Add the handler to the root Logger Logging. getlogger ( ""  ). Addhandler (console)  #  Set initial Log Level Logger = logging. getlogger ( ""  ) Level = Levels [log_level.upper ()] logger. setlevel (level)  Def Config_logging_plus (file_name = "  Log.txt  " , Log_level = " Noset  " , Remote_address = ( "  127.0.0.1  " , 8888), write_console = False ):  '''  @ Summary: config logging to write logs to remote service @ Param HOST: hostname or IP address of the log server @ Param port: port to be used for log server @ log_level: Log Level  '''  Logs_dir = OS. Path. Join (OS. Path. dirname ( _ File __ ), " Logs  "  )  If OS. Path. exists (logs_dir) And  OS. Path. isdir (logs_dir ):  Pass      Else  : OS. makedirs (logs_dir)  #  Format File Name      If File_name Is  None: file_name =OS. Path. splitext (SYS. argv [0]) [0] file_name = OS. Path. Join (logs_dir, "  % S _ % S. Log  " % (File_name, OS. getpid ()))  Else  : File_name = OS. Path. Join (logs_dir, file_name)  #  Clear old root logger handlers Logging. getlogger ( "" ). Handlers = []  # Define a rotating file Handler Rotatingfilehandler = logging. Handlers. rotatingfilehandler (filename = File_name, maxbytes = 1024*1024*50 , Backupcount = 5 ) Formatter = Logging. formatter ( "  % (Asctime) S % (name)-12 S % (levelname)-8 S % (Message) S  "  ) Rotatingfilehandler. setformatter (formatter)  #  Add log Handler Logging. getlogger ( ""  ). Addhandler (rotatingfilehandler)  If Write_console Is   Not None And Write_console = True:  #  Define a handler whitch writes messages to sys Console = Logging. streamhandler () console. setlevel (logging. notset)  #  Set a format which is simple for console use Formatter = logging. formatter ( "  % (Name)-12 s: % (levelname)-8 S % (Message) S  "  )  #  Tell the handler to use this format  Console. setformatter (formatter)  #  Add log Handler Logging. getlogger ( ""  ). Addhandler (console)  If Remote_address Is  Not None And Hasattr (remote_address, "  _ ITER __  " ) And Len (remote_address)> 1 :  #  Define a socket Handler Sockethandler = logging. Handlers. sockethandler (remote_address [0], remote_address [1 ]) Formatter = Logging. formatter ( " % (Asctime) S % (processname) S % (process) S % (name)-12 S % (levelname)-8 S % (Message) S  "  ) Sockethandler. setformatter (formatter)  #  Add log Handler Logging. getlogger ( ""  ). Addhandler (sockethandler)  #  Set initial Log Level Logger = logging. getlogger ( ""  ) Level = Levels [log_level.upper ()] logger. setlevel (level) 

The usage is simple. You only need to configure logging. The sample code is as follows:

 
ImportLoggingconfigloggingconfig. config_logging (file_name="Log. Log", Log_level ="Noset")
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.