Hi , I am new to python. I am trying to have a logrotate feature and also try to print the logs in formatted fashion.
So I have created two handlers one for log roataion and other for log formatting.

The log rotation is working fine as alone, but as soon as i enable format handler logger.addHandler(f_handler) , I am getting the error

Traceback (most recent call last):
File "C:\Python27\lib\logging\handlers.py", line 77, in emit
self.doRollover()
File "C:\Python27\lib\logging\handlers.py", line 142, in doRollover
os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file log_rotate.py, line 37
Traceback (most recent call last):
File "C:\Python27\lib\logging\handlers.py", line 77, in emit
self.doRollover()
File "C:\Python27\lib\logging\handlers.py", line 142, in doRollover
os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file log_rotate.py, line 38

What i don't understand is why adding an extra handler to existing logger is giving problem.
I request some experts to point me what is wrong i am doing here and guide me in right direction pls.

import logging
import time
from logging.handlers import RotatingFileHandler

def create_rotating_log(path):

    """
    Creates a rotating log
    """

#    date_strftime_format = "%d-%b-%y %H:%M:%S"
#    message_format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s'

    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)

    f_handler = logging.FileHandler(path)

    # add a rotating handler
    handler = RotatingFileHandler(path, maxBytes=1024,
                                  backupCount=5)
    logger.addHandler(handler)

    f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    f_handler.setFormatter(f_format)
#enabling this causing error WindowsError: [Error 32] The process cannot access the file because it is being used by another process
#    logger.addHandler(f_handler)

def logtheLogs():
    logger = logging.getLogger("Rotating Log")
    for i in range(3):
        logger.info("This is INFO test log line %s" % i)
        logger.error("This is ERR test log line %s" % i)

def MoreLogs():
    logger = logging.getLogger("Rotating Log")
    for i in range(3):
        logger.info("From More This is test log line %s" % i)
        logger.warning("From More This is WAR test log line %s" % i)

if __name__ == "__main__":
    log_file = "test.log"
    create_rotating_log(log_file)
    logtheLogs()
    MoreLogs()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.