0

I would like to create log file for each iteration of my script. I am creating logger for each iteration and i need close this opened file at the end of iteration because if I am not, I will recieve error Too many open files.

formatter = logging.Formatter('%(asctime)s %(message)s')

handler = logging.FileHandler(logging_file)
handler.setFormatter(formatter)

logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler) 

handler.close()

This should work but I recieved SyntaxError:

  File "start.py", line 73
    handler.close()
          ^
SyntaxError: invalid syntax

How should I close file handlers at the end of iteration? I tried to create handler and close it immediately to be sure there is no problem that I added handler to logger before, but the problem persist:

handler = logging.FileHandler(logging_file)
handler.close()
dorinand
  • 1,397
  • 1
  • 24
  • 49
  • 1
    `SyntaxError` implies there is some other issue in your actual code such as (possibly) an unmatched parenthesis but which is not shown in the code you posted. That SyntaxError is not due to `handler.close()`. The real source of the SyntaxError is on some preceding line. The closing of the handlers can be done [like this](https://stackoverflow.com/q/15435652/190597). – unutbu Jul 24 '18 at 17:11
  • 1
    Thank you for your reply, I tried to comment my code by blocks and run it, and I found mistake in my code ( missing `(` at the end of line). Now it works! Thank you. – dorinand Jul 24 '18 at 17:18
  • Additionally; you can look at RotatingFileHandler and use doRollover() as well. – sehafoc Jul 24 '18 at 17:49

0 Answers0