Search code examples
pythondjangodateloggingfile-structure

How am I able to create a file structure based on the current date?




I'm trying to log changes in our CMS to a logging file. I make use of the def logging_on_activity(). What I want is a new file for each day to keep the log records a bit organised.

I've already tried to use the datetime package to manually edit the filename.

def logging_on_activity(platform, appname, msg):
    import datetime
    now = datetime.datetime.now()

    if SITE_TYPE == SiteType.LOCAL:
        filename = 'path_to/../logs/' + str(now.__format__('%Y')) + '/' 
            + str(now.__format__('%m')) + '/' \
            + str(now.__format__('%d')) + '/logging.log'

    import datetime
    date = datetime.date.today().isoformat()
    time = datetime.datetime.now().strftime('%H:%m:%S')

    # Write to file
    with open(filename, 'a') as handle:
        handle.write("{0} {1} [ii] [{2:^19}] [{3:^19}]  {4}\n".format(date, time, platform, appname, msg))

The error I get is:

FileNotFoundError at ..
[Errno 2] No such file or directory: 'itdb_tools/logs/2019/09/11.log'

Example of what I want?
Date: 2019/09/11 -> System is writing to: path_to/../logs/2019/09/11/logging.log
Date: 2019/09/12 -> System is writing to: path_to/../logs/2019/09/12/logging.log

I hope what I want to achieve is possible.

Thanks in advance and I hope someone can help me in the right direction!


Solution

  • You have to create each new directory too. So you have to create the directory 2019, the directory 2019/09, the directory 2019/09/12, the directory 2019/09/11, etc. Python open can't just create directories on the fly implicitly. It only creates the leaf notes in the path.