python 同时向控制台和文件输出日志

march_on march_on 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我的代码如下:

#! /usr/bin/env python
#coding=utf-8
import logging
import traceback
import os
class Log(object):
def __init__(self, logger, file_handler_name):
self.loggerName = logger
self.logger = logging.getLogger(logger)
self.formatter = logging.Formatter( ("================================\n"
"time:%(asctime)s\nlogger:%(name)s\nlevel:%(levelname)s\n"
"file:%(filename)s\nfun:%(funcName)s\nlineno:%(lineno)d\n"
"message:%(message)s" ))

log_file_path = os.path.abspath(os.path.dirname(__file__)) + '/log/'
if os.path.isdir(log_file_path) == False:#如果log_file_path应该存在,则返回true
os.makedirs(log_file_path)
file_handler = logging.FileHandler(log_file_path + file_handler_name)
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(self.formatter)
self.logger.addHandler(file_handler)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(self.formatter)
self.logger.addHandler(console_handler)

def info(self, *msg):
try:
tmp = [msg[0]]
tmp.append(traceback.format_exc())
self.logger.info("\n****************\n".join(tmp))
except Exception, e:
print e

def error(self, *msg):
try:
tmp = [msg[0]]
tmp.append(traceback.format_exc())
self.logger.error("\n****************\n".join(tmp))
except Exception, e:
print e


if __name__ == "__main__":
test_log = Log('test', 'test.log')
test_log.info("this is a test log")
try:
print 1/0
except Exception, e:
msg = 'my message'
test_log.error(msg)


运行时发现只有test_log.error(msg)这个函数的日志分别写到文件和控制台了,这条日志 test_log.info("this is a test log")却没有写到控制台,请问问题出在哪里?
多谢
...全文

相关推荐

Python同时向控制台和文件输出日志logging的方法

在Python编程中,日志管理是一项重要的功能,特别是在开发和调试过程中,记录和追踪应用程序的行为至关重要。本文将深入探讨如何使用Python内置的`logging`模块来实现同时向控制台和文件输出日

weixin_38516863

Python 实现日志同时输出到屏幕和文件

在Python编程中,日志记录是一项非常重要的任务,它帮助开发者跟踪代码的运行情况,调试错误,以及在生产环境中监控程序的行为。本文将详细介绍如何在Python中实现日志同时输出到屏幕(控制台)和文件。

weixin_38629303

python将控制台输出保存至文件的方法

自定义记录器(Logger)Python标准库提供了`logging`模块用于日志记录,但如果你想自定义一个类来同时处理控制台和文件输出,可以创建一个类来实现这个功能,如下面的例子所示:```pythonimport

weixin_38514526

python 信息同时输出到控制台与文件的实例讲解

使用logging模块输出到控制台和文件logging模块是Python的标准库之一,专门用于输出日志。它提供了强大的配置功能,可以将日志输出到不同的目的地,比如控制台和文件。

weixin_38722721

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

本文主要介绍如何使用Python的logging模块将日志同时写入文件和控制台。首先,需要导入Python的logging模块。

weixin_38589812
评论 3
收藏 已收藏
分享
返回顶部
march_on
脚本语言 37,737 成员 34,208 内容