python (Logging) daily log file

Asked

Viewed 647 times

0

Hello, I would like to know how to create a log file for each day. Currently saved in a single file.

log_file = path.join(path.dirname(path.realpath(__file__)),"Log.txt")
logging.basicConfig(filename= log_file, level=logging.DEBUG, format='%(asctime)s %(levelname)s %(funcName)s => %(message)s')

Thanks for your cooperation.

1 answer

1


Just change the file name of Log.txt for the current date:

from datetime import date

log_file = path.join(path.dirname(path.realpath(__file__)), f"{date.today()}.txt")

The function date.today() return the current date in the format YYYY-MM-DD, thus getting the logs saved in 2019-03-18.txt, for example.

  • saved with the name {date.Today()}. txt, which change suggest I do?! , thanks in advance.

  • 1

    You used the prefix f indicating that it is a f-string? f"{date.today()}.txt"

  • Now it worked, I think it’s the version that was not accepting the f-string, I used log_file = path.join(path.dirname(path.realpath(__file__)), "{}.txt".format(date.today())) and it worked, thank you :)

  • Ah, yes. The f-strings are only available in versions 3.6+ of Python.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.