我正在创建记录器文件。现在我需要根据日期创建记录器文件。 我的下面的代码只创建一个日志文件。但我需要创建一个新的 日志文件date wise.am不知道如何每天创建日志文件。
使用以下代码创建日志文件。
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, request, jsonify
from time import strftime
import traceback
app = Flask(__name__)
@app.route("/")
def get_index():
return "Welcome to Flask! "
@app.route("/data")
def get_hello():
data = {
"Name":"Ivan Leon",
"Occupation":"Software Developer",
"Technologies":"[Python, Flask, MySQL, Android]"
}
return jsonify(data)
@app.route("/error")
def get_json():
return non_existent_variable # ---> intentional <---
@app.after_request
def after_request(response):
# this if avoids the duplication of registry in the log,
# since that 500 is already logged via @app.errorhandler
if response.status_code != 500:
ts = strftime('[%Y-%b-%d %H:%M]')
logger.error('%s %s %s %s %s %s',
ts,
request.remote_addr,
request.method,
request.scheme,
request.full_path,
response.status)
return response
@app.errorhandler(Exception)
def exceptions(e):
ts = strftime('[%Y-%b-%d %H:%M]')
tb = traceback.format_exc()
logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s',
ts,
request.remote_addr,
request.method,
request.scheme,
request.full_path,
tb)
return "Internal Server Error", 500
if __name__ == '__main__':
handler = RotatingFileHandler('app.log', maxBytes=100000, backupCount=3)
logger = logging.getLogger('__name__')
logger.setLevel(logging.INFO)
logger.addHandler(handler)
app.run()
答案 0 :(得分:0)
每次运行代码时动态创建日志文件名。 像
这样的事情import datetime
now = datetime.datetime.now()
file_name = "app_" + str(now) + ".log"
然后在代码中使用此文件名而不是“app.log”。这将在每次代码运行时创建一个日志。如果您希望它仅为每天创建日志,则可以使用。
now = datetime.date.today()
我希望它有所帮助!
答案 1 :(得分:0)
试试这个:
import logging
import logging.handlers
def get_logger(filename='', name=''):
log_file_name = filename
logging_level = logging.DEBUG
# set TimedRotatingFileHandler for root
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
# use very short interval for this example, typically 'when' would be 'midnight' and no explicit interval
handler = logging.handlers.TimedRotatingFileHandler(log_file_name, when='midnight', backupCount=10)
handler.suffix = "%Y-%m-%d"
handler.setFormatter(formatter)
logger = logging.getLogger(name) # or pass string to give it a name
logger.addHandler(handler)
logger.setLevel(logging_level)
return logger
然后,您可以在任何需要记录的地方调用此方法。