码迷,mamicode.com
首页 > 编程语言 > 详细

python 通过logging写入日志到文件和控制台

时间:2015-06-16 11:13:27      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:message   python   import   控制台   

#!/usr/bin/python
#-*- coding:utf-8 -*-

import logging

# 创建一个logger 
logger = logging.getLogger(‘mytest‘)  
logger.setLevel(logging.DEBUG)

# 创建一个handler,用于写入日志文件 
fh = logging.FileHandler(‘test.log‘)
fh.setLevel(logging.DEBUG)

# 再创建一个handler,用于输出到控制台 
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# 定义handler的输出格式 
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 给logger添加handler 
logger.addHandler(fh)
logger.addHandler(ch)

# 记录一条日志 
logger.info(‘python logging test‘)


[root@localhost tmp]# python fun1.py 

2015-06-16 09:09:03,732 - mytest - INFO - python logging test

[root@localhost tmp]# cat test.log 

2015-06-16 09:09:03,732 - mytest - INFO - python logging test


本文出自 “网络收藏夹” 博客,请务必保留此出处http://liyaoyi.blog.51cto.com/442933/1662212

python 通过logging写入日志到文件和控制台

标签:message   python   import   控制台   

原文地址:http://liyaoyi.blog.51cto.com/442933/1662212

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!