How to clear the log file and write it again?

I create a log file this way:

global logger logger = logging.getLogger("plus_dig_cname") logger.setLevel(logging.DEBUG) fh = logging.FileHandler( fdoc_log + "/plus_dig_cname.log" ) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) 

and when plus_dig_cname.log is larger than 300 MB, I process it with a shell script, the main process:

  mv $LOG_DIR/$1 $LOG_DIR/$1.bk [ $? -ne 0 ] && return 1 touch $LOG_DIR/$1 [ $? -ne 0 ] && return 1 chmod 666 $LOG_DIR/$1 [ $? -ne 0 ] && return 1 

just mv and tap new.
The problem is that the registrar cannot use anything in the plus_dig_cname.log file. Logs cannot work.
Perhaps this can be solved by:

 with open( "plus_dig_cname.log", "w" ): pass 

this way you can get the new log file using Python. But I want to get a new Bash log file.

So why can't the log work after "mv touch chmod"?

thanks

+4
source share
2 answers

Use RotatingFileHandler to handle this for you.

For instance:

 MAX_SIZE = 300 * 1024 * 1024 LOG_PATH = fdoc_log + "/plus_dig_cname.log" fh = logging.handlers.RotatingFileHandler(LOG_PATH, maxBytes=MAX_SIZE, backupCount=5) 

This will create 5 backups of 300 MB each.

+4
source

A file is opened when FileHandler() or when it is first written to it. If you move the file; he left.

You can use logging.handlers.RotatingFileHandler since @sberry suggested rotating the file using Python.

If you arbitrarily rotate the log files, for example using logrotate , you can notify your script that the file has disappeared, for example, restart it or send a signal at the postrotate stage.

Your script may automatically open the file if you use something like inotify to detect the change. Compare how tail -f and tail -f .

+1
source

Source: https://habr.com/ru/post/1434536/


All Articles