Created
February 16, 2021 12:22
-
-
Save netkiller/c87398338d314f44d681e6b62fe9184c to your computer and use it in GitHub Desktop.
这是一个演示日志切割的python程序
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# -*- coding: UTF-8 -*- | |
#================================================================================ | |
# 这是一个演示日志切割的python程序 | |
# 作者: netkiller | [email protected] | http://www.netkiller.cn | |
#================================================================================ | |
import time,os,signal,sys | |
pidfile = "/tmp/netkiller.pid" | |
logdir = "/tmp" | |
logfile = open("/dev/null", "a+") | |
loop = True | |
def savepid(pid): | |
f = open(pidfile,"w") | |
f.write(pid) | |
f.flush() | |
f.close() | |
def getpid(): | |
f = open(pidfile,"r") | |
pid = f.readline() | |
f.close() | |
# print(pid) | |
return int(pid) | |
def createlog(): | |
global logfile | |
logfile.flush() | |
logfile.close() | |
filename = time.strftime(logdir + "/netkiller-%Y-%m-%d.%H-%M-%S.log",time.localtime()); | |
# print(filename) | |
logfile = open(filename,mode="a+") | |
return filename | |
def log(tag,msg): | |
logfile.write(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) + " "+tag+" "+ msg +"\r\n") | |
logfile.flush() | |
def signalHandler(signum,frame): | |
global loop | |
# print("HUP OK",str(signum)); | |
if signum == signal.SIGHUP : | |
filename = createlog() | |
log("WARN","Create log file " + filename) | |
elif signum == signal.SIGINT: | |
loop = False | |
def start(): | |
if os.path.isfile(pidfile) : | |
print("error") | |
sys.exit() | |
pid = os.fork() | |
if pid == 0 : | |
# print(os.getpid()) | |
savepid(str(os.getpid())) | |
createlog() | |
log("WARN","Start!!!") | |
while loop: | |
# 业务逻辑 | |
log("INFO","Hello world!!!") | |
# 业务逻辑 | |
time.sleep(1) | |
log("WARN","Exit!!!") | |
logfile.close() | |
def stop(): | |
try: | |
os.kill(getpid(), signal.SIGINT) | |
except ProcessLookupError as identifier: | |
pass | |
os.remove(pidfile) | |
def reloadlog(): | |
try: | |
os.kill(getpid(), signal.SIGHUP) | |
except ProcessLookupError as identifier: | |
pass | |
def usage(): | |
print(sys.argv[0] + " start | stop | reload") | |
if __name__ == "__main__": | |
# print(sys.argv) | |
signal.signal(signal.SIGHUP, signalHandler) | |
signal.signal(signal.SIGINT, signalHandler) | |
signal.alarm(5) | |
if len(sys.argv) > 1: | |
arg = sys.argv[1] | |
if arg == "start" : | |
start() | |
elif arg == "stop": | |
stop() | |
elif arg == "reload": | |
reloadlog() | |
else: | |
usage() | |
else: | |
usage() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment