0

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)

1
  • 1
    Why don't you use the python logging framework? It is standard and good Commented Oct 29, 2019 at 12:37

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.