1

I am creating a logger with unique name as per object unique label during creating of a object. I want different log files for different objects. It is creating only single file and appending all logs to it

I have created 5 instance of class student with incremented label from 1 - 6 in constructor(init), I create a logger object with unique name by appending the label to it. After run only one file is created instead of 5 individual files which was expected

#python2.7
import logging
class student:
    def __init__(self,label):
        self.label = label
        file_name ="Log_Rollno" + str(self.label)
        logging.basicConfig(filename=file_name,format='%(asctime)s %(message)s',filemode='w')
        print "CREATED " + file_name
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        self.logger.info("Message from Object" + str(self.label))

if __name__ == "__main__":
    for i in range(1,6):
        student_obj = student(i)

I expect : Individual files as per objects unique label (Log_Rollno1, Log_Rollno2)

Actual Result: Messages from all created objects get appended to only one file

(File Name : Log_Rollno1) 2019-07-16 12:52:49,884 Message from Object1 2019-07-16 12:52:49,890 Message from Object2 2019-07-16 12:52:49,894 Message from Object3 2019-07-16 12:52:49,898 Message from Object4 2019-07-16 12:52:49,904 Message from Object5

2
  • I think this is because you are setting the base logging to the filename logging.basicConfig(filename=file_name,format='%(asctime)s %(message)s',filemode='w') surely this should be in the config of each of the loggers that you spawn. Commented Jul 16, 2019 at 7:33
  • 1
    Is this what you are looking for ? stackoverflow.com/questions/11232230/… Commented Jul 16, 2019 at 7:37

1 Answer 1

2

You can use logging.basicConfig() only once. It configures the root logger and if there is a handler attached already it will return silently without doing anything.

The documentation states:

This function does nothing if the root logger already has handlers configured for it.

In your case the first instance will configure the logger. Instances created later will not.

You might want to configure the logger manually by attaching a Handler to it instead of using logging.basicConfig().

Example in the docs showing how to attach a handler.

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.