Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the log file and write it again?

Tags:

python

I create the log file by 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 the size of plus_dig_cname.log is bigger than 300MB,I handle it by a shell script, the main process is:

 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 it and touch a new one.
The problem is the logger can't wirte anything in the file of plus_dig_cname.log. The logging can't work.
Maybe it can be solved it by:

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

this way can get a new log file by Python. But i want to get the new log file by Bash.

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

Thank you

like image 880
lxgeek Avatar asked Sep 17 '12 06:09

lxgeek


1 Answers

Use a RotatingFileHandler to have this handled for you.

For example:

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 300MB each.

like image 61
sberry Avatar answered Nov 15 '22 13:11

sberry