Alessandrini
Alessandrini

Reputation: 191

Python - creating and outputing a logfile to a different folder in a loop

I have this Logger class that I use to write to the console and to file. However, the requirements have changed and I want to output the log file to a different folder using a for loop

import sys
import os
#from pathlib import Path

class Logger(object):
    def __init__(self, name, mode="a"):
         self.stderr = sys.stderr
         self.stdout = sys.stdout
         self.log = open(name, mode)
    def __del__(self):
         sys.stderr = self.stderr
         sys.stdout = self.stdout
         self.log.close()
    def write(self, message):
         self.stdout.write(message)
        #self.stderr.write(message)
         self.log.write(message)
    def flush(self):
         self.log.flush()



def printing(x):
     print(x)

def output_path(path, x):
     fname = os.path.join(path, "log_" + str(x) + ".txt")
     if os.path.exists(fname): os.remove(fname)
     sys.stdout = Logger(fname)

for i in range(3):
     path = "../../../test/{}".format(str(i))
     if not os.path.exists(path):
         os.makedirs(path)

     output_path(path, i)
     printing(i + "Piece")

When I run this code, the 3 log files are created, however, the output in the log files is not what I want.

Current Output**

Log_0.txt -> 0piece
             1piece
             2piece 

Log_1.txt -> 1piece
             2piece

Log_2.txt -> 2piece

Preferred Output

Log_0.txt -> 0piece

Log_1.txt -> 1piece

Log_2.txt -> 2piece

As you can see, I am not very familiar with the Logger behaviour, my question is how do I create my log file, write to it and close it after every iteration (I want to be able to generalise this to nested loops)

Upvotes: 0

Views: 149

Answers (1)

Jelle
Jelle

Reputation: 31

You could look into the python logging module. It is full of features and easy to use. It has a a RotatingFileHandler that does rotate over files automatically. See for an example: How to use Python's RotatingFileHandler

Upvotes: 1

Related Questions