Python自定义写日志

文章目录

  • 记录代码出错的位置
  • 分日期保存文件
  • traceback+写文件

记录代码出错的位置

def f2(b, a):
    print(b - a)

def f1(a, b):
    return f2(b, a)

def try_log(func, *args, **kwargs):
    from time import strftime
    from traceback import format_exc
    try:
        func(*args, **kwargs)
    except:
        error = format_exc()
        print('\033[031m', error, '\033[0m', sep='\n')
        with open('log_%s.txt' % strftime('%Y-%m-%d'), 'a', encoding='utf-8') as f:
            f.write('%s\n' % error)

if __name__ == '__main__':
    try_log(f1, 1, b='2')

分日期保存文件

def write_log(*args):
    from time import strftime
    ymd = strftime('%Y%m%d')
    with open('%s.log' % ymd, 'a', encoding='utf-8') as f:
        for i in args:
            f.write('%r\n' % i)
        f.write('\n')

traceback+写文件

import os
from traceback import format_exc
from time import strftime
_path = os.path.dirname(__file__)
_get_abs_path = lambda path: os.path.normpath(os.path.join(_path, path))

def traceback_func(func, *args, **kwargs):
    try:
        value = func(*args, **kwargs)
        return value
    except:
        error = format_exc()  # 在线程中失效
        write_log(error, *args, **kwargs)

def try_func(func, *args, **kwargs):
    try:
        value = func(*args, **kwargs)
        return value
    except Exception as error:
        write_log(error, *args, **kwargs)

def write_log(*args, **kwargs):
    if 'fname' in kwargs:
        fname = kwargs.pop('fname')
    else:
        fname = _get_abs_path(strftime('%Y-%m-%d') + '.txt')
    with open(fname, 'a', encoding='utf-8') as f:
        for i in args:
            f.write('{}\n'.format(i))
            print('\033[031m', i, '\033[0m')
        for i in kwargs.values():
            f.write('{}\n'.format(i))
            print('\033[031m', i, '\033[0m')
        f.write('\n')

def remove():
    for fname in os.listdir(_path):
        if '.txt' in fname:
            abs_fname = _get_abs_path(fname)
            print(abs_fname)
            os.remove(abs_fname)

if __name__ == '__main__':
    """清空日志,谨慎启动"""
    remove()

你可能感兴趣的:(Python实用技巧)