0

I want to create a log file in Python 3.6 & save the time for different operations.

So I used this code:

def create_logger(logFile, fileLogLevel, streamLogLevel): # create logger for "Sample App" logger = logging.getLogger('Seller Explosion') logger.setLevel(logging.INFO) # create file handler which logs WARNING messages fh = logging.FileHandler(logFile, mode='w') fh.setLevel(fileLogLevel) # create console handler with a higher log level ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(streamLogLevel) # create formatter and add it to the handlers formatter = logging.Formatter('[%(asctime)s] %(levelname)8s --- %(message)s ' + '(%(filename)s:%(lineno)s)', datefmt='%Y-%m-%d %H:%M:%S') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(ch) logger.addHandler(fh) return logger 

While executing the code I'm using following command

logger = create_logger('<path to my folder>/TimeLog.log', logging.WARNING, logging.WARNING) startTime=time.ctime() logTime="Start Time for uploading: "+startTime logger.info(logTime) 

But while going to my path, I'm seeing that TimeLog.log is a blank file with size 0 byte. Can you please suggest me what error I'm making?

0

1 Answer 1

1

You set your handlers to filter on the WARNING level:

logger = create_logger(..., logging.WARNING, logging.WARNING) 

and

fh.setLevel(fileLogLevel) # ... ch.setLevel(streamLogLevel) 

then logged an INFO level message. INFO is a lower, less severe level from WARNING, so is filtered out by the handler.

You need to log at WARNING level or higher (so WARNING, ERROR or CRITICAL, or a numeric value of 30 and up), or configure your handlers to handle lower levels (so INFO, DEBUG, or NOTSET, or a numeric value of 20 or below).

For example, logger.warn(logTime) causes data to be added to your log file. And if you used logging.INFO for the second argument to create_logger(), the logger.info() call would also have the same effect.

From the Handler.setLevel() method documentation:

Sets the threshold for this handler to level. Logging messages which are less severe than level will be ignored. When a handler is created, the level is set to NOTSET (which causes all messages to be processed.

Bold emphasis mine; also see the Logging levels section for their ordering and numeric values.

Note that creating a log message with a timestamp in the log message is rather redundant, as your log format already includes a timestamp:

>>> startTime = time.ctime() >>> logTime = "Start Time for uploading: " + startTime >>> logger.warn(logTime) [2018-01-17 16:36:20] WARNING --- Start Time for uploading: Wed Jan 17 16:36:20 2018 (<stdin>:1) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.