0

Log rotation is working fine when I log to the current working directory, but get a PermissionError when I am trying to log to a separate directory within the current directory.

Is there a way to handle this without a need for -

  1. additional function to be written
  2. log to the cwd and move the renamed file to the log directory post rotation?

Based on the docs, I have tried adding delay=True without any luck.

I have also reviewed other posts that talk about the PermissionError but are slightly different to the issue here.

Any insights would be helpful. Thanks

log_file_name = os.path.join(os.getcwd()+'\\'+'logs'+'\\'+'sample.log')

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(funcName)s()] [%(levelname)s] : %(message)s')
file_handler = handlers.TimedRotatingFileHandler(log_file_name, when='midnight', backupCount=100, delay=True)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

Timus
  • 10,974
  • 5
  • 14
  • 28
  • The error is likely to be context related. On Windows, a file can only be opened once and all subsequent *open* calls will raise an error. Are you sure that 1/ only one instance of your process is running and 2/ no other process tries to open the log files? – Serge Ballesta Sep 22 '21 at 08:07
  • @SergeBallesta - sure.. the one raising the error is the only instance that is accessing the file. There are no processes other than the main program that is accessing the file. As I mentioned, it works perfectly fine when I use ``file_handler = handlers.TimedRotatingFileHandler('sample.log', when='midnight', backupCount=100)`` i.e. logging in the current directory – Jagajith Nambiar Sep 22 '21 at 08:50
  • Hmm... error messages of the Windows OS are known not to be always accurate... Did you control twice that the directory exists and is writable by the process? – Serge Ballesta Sep 22 '21 at 09:02
  • @SergeBallesta - yes. In my testing of both approaches, I could see there were no issues rotating the files and logging when writing to current directory – Jagajith Nambiar Sep 22 '21 at 09:38

0 Answers0