Skip to content

Instantly share code, notes, and snippets.

@Drunkar
Last active Oct 19, 2021
Embed
What would you like to do?
# coding: utf-8
import logging
import traceback
import argparse
import time
from logging.handlers import RotatingFileHandler
from contextlib import contextmanager
logger = logging.getLogger(__name__)
@contextmanager
def time_logger(label):
start = time.time()
yield
end = time.time()
logger.info("{}: {:.3f} sec consumed.".format(label, end - start))
def main(args):
try:
with time_logger("1.first_process"):
print("Hello, world!")
except Exception as e:
logger.error("{}:{}".format(e, traceback.format_exc())
if __name__ == '__main__':
# args
parser = argparse.ArgumentParser(
description="Awesome CLI.")
parser.add_argument(
"-d", "--debug", action="store_true", help="Debug mode.")
args = parser.parse_args()
# logger
if args.debug:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.INFO
formatter = logging.Formatter(
fmt="[%(asctime)s] %(levelname)s [%(name)s/%(funcName)s() at line %(lineno)d]: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
logger.setLevel(LOG_LEVEL)
# stdout
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel(LOG_LEVEL)
logger.addHandler(stream_handler)
# log file
file_handler = RotatingFileHandler(filename="./log.txt", maxBytes=2000, backupCount=5)
file_handler.setFormatter(formatter)
file_handler.setLevel(LOG_LEVEL)
logger.addHandler(file_handler)
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment