python 日志打印功能学习

发布时间:2020-01-01编辑:脚本学堂
python扩展了日志打印功能,感觉比java自带的还好,和log4j很类似。

python扩展了日志打印功能,感觉比java自带的还好,和log4j很类似。

先说一种不用配置文件的:
文件名:log.py

# -*- coding: gb2312 -*-
import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='./AutoUpdate.log',
                    filemode='w')

console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

## 
# console = logging.StreamHandler()
# console = setLevel(logging.DEBUG)
# formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# console.setFormatter(formatter)
# logging.getLogger('').addHandler(console)

def getLogging(name):
    return logging.getLogger(name)

文件名:test.py

import log

testlog = log.getLogging('test')
testlog.error( "~~~~~~~~~~~~~~test1.")
testlog.info( "~~~~~~~~~~~~~~test2." )
testlog.exception( "~~~~~~~~~~~~~~~~~~~~~~~~~test3.")

用过log4j的人不会陌生这种用法。如果你对log4j有疑惑,请参看相关文档

第二种使用配置文件的:

复制代码 代码如下:

# logging.conf

[loggers]
keys=root,example

[handlers]
keys=consoleHandler,rotateFileHandler

[formatters]
keys=simpleFormatter

[formatter_simpleFormatter]
format=[%(asctime)s](%(levelname)s)%(name)s : %(message)s

[logger_root]
level=DEBUG
handlers=consoleHandler,rotateFileHandler

[logger_example]
level=DEBUG
handlers=consoleHandler,rotateFileHandler
qualname=example
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=('test.log', 'a', 10000, 9)

文件名:test2.py

import logging
import logging.config

logging.config.fileConfig("logger.conf")

#create logger
logger = logging.getLogger("example")

#"application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

logHello = logging.getLogger("hello")
logHello.info("Hello world!")

其中值得注意的是args的含义。