学以致用

focus on Python , C++, and some interest in Go and R

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

为了调试方便,特意将python的logging模块封装了一下,支持同时向console和file输出,支持日志文件回滚。
(1)myloggingconfig.py

View Code
# -*- coding: utf-8 -*-

'''
Created on 2011-8-24
主要用途:
对程序中所使用的loggong模式做一般性配置
@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)-12s %(levelname)-8s %(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)-12s %(levelname)-8s %(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)-12s: %(levelname)-8s %(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)具体使用方法

import logging
logger = logging.getLogger(__name__)


if __name__ == "__main__":
import myloggingconfig
msg = “this is just a test”
logger.info(msg)

如果想动态更改logging的level,可以通过logging.getLogger("").setLevel(level)进行更改。

posted on 2012-02-01 13:39  Jerry.Kwan  阅读(1734)  评论(0编辑  收藏  举报