log.py (1247B)
1 # See LICENSE file for copyright and license details. 2 3 """ 4 Logging functions 5 """ 6 7 from time import strftime 8 from os import makedirs 9 from os.path import join 10 import sys 11 12 from lib.config import logdir 13 14 15 def timestamp(): 16 """ 17 Return current time in a certain format. 18 """ 19 return strftime("%Y/%m/%d %H:%M:%S") 20 21 22 def die(msg, tofile=True): 23 """ 24 Log error and exit with exitcode 1 25 """ 26 msg = "%s [ERR] %s" % (timestamp(), msg) 27 print(msg) 28 if tofile: 29 logtofile('amprolla.txt', msg+'\n') 30 sys.exit(1) 31 32 33 def warn(msg, tofile=True): 34 """ 35 Log warning and continue 36 """ 37 msg = "%s [WARN] %s" % (timestamp(), msg) 38 print(msg) 39 if tofile: 40 logtofile('amprolla.txt', msg+'\n') 41 42 43 def info(msg, tofile=False): 44 """ 45 Log informational message and continue 46 """ 47 msg = "%s [INFO] %s" % (timestamp(), msg) 48 print(msg) 49 if tofile: 50 logtofile('amprolla.txt', msg+'\n') 51 52 53 def logtofile(filename, text, redo=False): 54 """ 55 Log given text to a given file. 56 If redo is True, rewrites the file 57 """ 58 makedirs(logdir, exist_ok=True) 59 wrt = 'a' 60 if redo: 61 wrt = 'w' 62 lfile = open(join(logdir, filename), wrt) 63 lfile.write(text) 64 lfile.close()