[英]Python logging to write all level logs to file
import logging
def set_logging():
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logger = logging.getLogger('simple_example')
fl = logging.FileHandler("myapp.log")
fl.setLevel(logging.INFO)
logger.addHandler(fl)
return logger
if __name__ == "__main__":
logger = set_logging()
logger.info('infoooo')
logger.error('erorrrr')
Output:
/home/admin# python logging.py
09/08/2019 02:40:36 PM INFO infoooo
09/08/2019 02:40:36 PM ERROR erorrrr
/home/admin# cat myapp.log
infoooo
erorrrr
If i comment out logging.basicConfig() line in above code, output is not seen in console and only 'erorrrr' message is written to file. 如果我在上面的代码中注释了logging.basicConfig()行,则在控制台中看不到输出,并且仅将“ erorrrr”消息写入文件。 What can i change in the above code to write all level logs to file without writing anything to console?
我可以在上述代码中进行哪些更改,以将所有级别的日志写入文件,而无需向控制台写入任何内容?
If you just add logger.propagate = False
this line in set_logging
function. 如果仅添加
logger.propagate = False
,则set_logging
函数中的这一行。 It will write all levels of log into the file and will not be shown on the console. 它将所有级别的日志写入文件,并且不会在控制台上显示。
def set_logging():
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logger = logging.getLogger('simple_example')
fl = logging.FileHandler("myapp.log")
fl.setLevel(logging.INFO)
logger.addHandler(fl)
logger.propagate = False # added this line to disable console logs.
return logger
You can use logger.propagate = False
to disable console logging. 您可以使用
logger.propagate = False
禁用控制台日志记录。
import logging
def set_logging():
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logger = logging.getLogger('simple_example')
logger.propagate = False
fl = logging.FileHandler("myapp.log")
fl.setLevel(logging.INFO)
logger.addHandler(fl)
return logger
if __name__ == "__main__":
logger = set_logging()
logger.info('infoooo')
logger.error('erorrrr')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.