Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - 仅记录到文件而不是记录屏幕.DEBUG(Log only to a file and not to screen for logging.DEBUG)

I have the following script that I want only the "DEBUG" log messages to be logged to the file, and nothing to the screen.

(我有以下脚本,我只希望将“ DEBUG”日志消息记录到文件中,而什么也不记录到屏幕中。)

from flask import Flask, request, jsonify
from gevent.pywsgi import WSGIServer
import usaddress
app = Flask(__name__)

from logging.handlers import RotatingFileHandler
import logging
#logging.basicConfig(filename='error.log',level=logging.DEBUG)


# create a file to store weblogs
log = open('error.log', 'w'); log.seek(0); log.truncate();
log.write("Web Application Log
"); log.close();

log_handler = RotatingFileHandler('error.log', maxBytes =1000000, backupCount=1)

formatter = logging.Formatter(
    "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"
    )
log_handler.setFormatter(formatter)
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(log_handler)

@app.route('/')
def hello():
  return "Hello World!"

@app.route("/parseAddress", methods=["POST"])
def parseAddress():
  address = request.form['address']
  return jsonify(usaddress.tag(address)), 200

if __name__ == '__main__':
#  app.run(host='0.0.0.0')
  http_server = WSGIServer(('', 5000), app, log=app.logger)
  http_server.serve_forever()

But right now even "INFO" messages are being logged to the file and to the screen.

(但是现在,即使“ INFO”消息也被记录到文件和屏幕上。)

How can I have only the "DEBUG" messages logged to the file and nothing to the screen?

(如何只将“调试”消息记录到文件中,而什么都没有记录到屏幕上?)

  ask by david translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I did some interactive testing and it looks like app.logger is a logger named with python file

(我进行了一些交互式测试,看来app.logger是一个以python文件命名的记录器)

print(app.logger.name) # filename

and it has one handler

(它有一个处理程序)

print(app.logger.handlers) # [<StreamHandler <stderr> (NOTSET)>]

A handler with level logging.NOTSET processes all messages (from all logging levels).

(具有级别日志记录的处理程序logging.NOTSET处理所有消息(来自所有日志记录级别)。)

So when you set app.logger.setLevel(logging.DEBUG) then all debug and higher logs will be passed to handlers and all of them will appear on stderr.

(因此,当您设置app.logger.setLevel(logging.DEBUG)所有调试和更高级别的日志都将传递给处理程序,并且所有它们都将出现在stderr上。)

To log absolutely nothing on the screen you have to manually remove StreamHandler:

(要在屏幕上完全不记录任何内容,您必须手动删除StreamHandler:)

app.logger.handlers.pop(0)

and to log DEBUG and higher to the file set logging level also on the handler

(并在处理程序上将DEBUG和更高级别记录到文件集日志记录级别)

log_handler.setLevel(logging.DEBUG)

Python logging is quite complicated.

(Python日志记录非常复杂。)

See this logging flow chart for better understanding what is going on :)

(请参阅此日志记录流程图以更好地了解正在发生的事情:))

EDIT: to log only one specific level you need custom Filter object:

(编辑:仅记录一个特定级别,您需要自定义过滤器对象:)

class LevelFilter:
    def __init__(self, level):
        self._level = level

    def filter(self, log_record):
        return log_record.levelno == self._level

log_handler.setLevel(logging.DEBUG)
log_handler.addFilter(LevelFilter(logging.DEBUG))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...