經常使用的一個python logging封裝,支援同時向console和檔案輸出

來源:互聯網
上載者:User

為了調試方便,特意將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)變更。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.