For ease of debugging, the python logging module is encapsulated to support simultaneous output to the console and file, and log file rollback.
(1) myloggingconfig. py
View code
# -*-Coding: UTF-8 -*-
'''
Created on 2011-8-24
Main purpose:
PairProgramGeneral configuration of the loggong mode used in
@ Author: jerrykwan
'''
Import Logging
Import Logging. handlers
Import OS
Levels = { ' 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
Logs_dir = OS. Path. Join (OS. Path. curdir, " Logs " )
If OS. Path. exists (logs_dir) And OS. Path. isdir (logs_dir ):
Pass
Else :
OS. mkdir (logs_dir)
# Define a rotating file Handler
Rotatingfilehandler = logging. Handlers. rotatingfilehandler (filename = " ./Logs/log.txt " ,
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 ()
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 the handler to the root Logger
Logging. getlogger ( "" ). Addhandler (console)
# Set initial Log Level
Logger = logging. getlogger ( "" )
Logger. setlevel (logging. notset)
(2) Usage
ImportLogging
Logger = logging. getlogger (_ Name __)
If _ Name __="_ Main __":
ImportMyloggingconfig
MSG = "ThisIsJust a test"
Logger.info (MSG)
To dynamically change the logging level, you can use logging. getlogger (""). setlevel (level) to change it.