栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将日志消息同时写入日志文件和控制台?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将日志消息同时写入日志文件和控制台?

不,它不会同时写入两者。

print()
只会写入控制台。关于原始代码的简短说明。我想您在
message
某处定义,但是代码仍然不正确。您需要
a
open
语句中使用引号,例如:

open("logfile.log", "a")

因为我认为您是要附加到文件中。否则,您的代码将抛出一个

NameError
因为
a
未定义的变量。

但是,正如其他人所说,您应该强烈考虑使用日志记录模块。这是一个如何同时写入控制台和日志文件的简单示例。该代码部分源自此处和此处:

import inspectimport loggingdef function_logger(file_level, console_level = None):    function_name = inspect.stack()[1][3]    logger = logging.getLogger(function_name)    logger.setLevel(logging.DEBUG) #By default, logs all messages    if console_level != None:        ch = logging.StreamHandler() #StreamHandler logs to console        ch.setLevel(console_level)        ch_format = logging.Formatter('%(asctime)s - %(message)s')        ch.setFormatter(ch_format)        logger.addHandler(ch)    fh = logging.FileHandler("{0}.log".format(function_name))    fh.setLevel(file_level)    fh_format = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s')    fh.setFormatter(fh_format)    logger.addHandler(fh)    return loggerdef f1():    f1_logger = function_logger(logging.DEBUG, logging.ERROR)    f1_logger.debug('debug message')    f1_logger.info('info message')    f1_logger.warn('warn message')    f1_logger.error('error message')    f1_logger.critical('critical message')def f2():    f2_logger = function_logger(logging.WARNING)    f2_logger.debug('debug message')    f2_logger.info('info message')    f2_logger.warn('warn message')    f2_logger.error('error message')    f2_logger.critical('critical message')def main():    f1()    f2()    logging.shutdown()main()

由于记录器对象可以具有多个处理程序,因此我们可以创建写入不同位置的多个处理程序。在我的代码中,该

function_logger
函数创建一个特定于其调用函数的logger对象。

该功能

f1()
DEBUG
级别消息及更高级别的消息记录到一个文件中
f1.log
,同时将
ERROR
级别消息及更高级别的消息写入控制台,每种消息的格式不同。

f2()
但是,该功能不记录任何内容到控制台,而仅将
WARNING
级别消息记录到其日志文件中
f2.log
。运行此脚本一次,将在控制台上产生以下输出:

2012-07-20 10:46:38,950 - f1  - error message2012-07-20 10:46:38,953 - f1  - critical message

该输出分别在

f1.log
和中
f2.log

f1.log

2012-07-20 10:46:38,950 - 26 - DEBUG    - debug message2012-07-20 10:46:38,950 - 27 - INFO     - info message2012-07-20 10:46:38,950 - 28 - WARNING  - warn message2012-07-20 10:46:38,950 - 29 - ERROR    - error message2012-07-20 10:46:38,953 - 30 - CRITICAL - critical message

f2.log

2012-07-20 10:46:38,960 - 36 - WARNING  - warn message2012-07-20 10:46:38,960 - 37 - ERROR    - error message2012-07-20 10:46:38,960 - 38 - CRITICAL - critical message


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639044.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号