Python下定义输出日志

# 话不多说,直接看代码,,, 

# -*- coding:UTF-8 -*-
# python version: 2.7.15

#脚本名, 日志名,日志路径

import os
import sys
import time
import datetime
import socket


# 定义日志路径
g_log_directory = "E:\logs"

g_current_date = time.strftime('%Y-%m-%d')
g_scripi_name = sys.argv[0].split("\\")[-1]

    

#定义一个类,拼接出日志名称 脚本名+当前日期+'.log'
class addStrings:
     
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    
    def __str__(self):
        return self.a + self.b + self.c
    
    def __add__(self, other):
        return self.a + self.b

if __name__ == "__main__":
    g_log_name = str(addStrings(str(g_scripi_name),str(g_current_date),".log" ))

print "log_name:",g_log_name


print "log_path:",g_log_directory




class print_log(object):
    @staticmethod   #静态类   信息
    def info(*message):
        out_message = print_log.timeStamp() + ' ' + 'INFO: ' + str(message) 
        print_log.write(out_message)

    @staticmethod   #静态类   警告
    def warn(*message):
        out_message = print_log.timeStamp() + ' ' + 'WARN: ' + str(message)
        print_log.write(out_message)

    @staticmethod   #静态类  错误
    def error(*message):
        out_message = print_log.timeStamp() + ' ' + 'ERROR: ' + str(message)
        print_log.write(out_message)

    @staticmethod
    def write(message):
        log_path = os.path.join(g_log_directory, g_log_name)
        with open(log_path, 'a+') as f:
            f.write(message)
            f.write('\n')

    @staticmethod
    def timeStamp():
        local_time = time.localtime(time.time())
        return time.strftime("%Y-%m-%d %H:%M:%S", local_time)

if __name__ == "__main__":
    #print Print_log.timeStamp()
    print_log.info("hello world")
    pass
    
aa = 1234
print_log.info(aa)

print_log.info("log_path: ",g_log_directory)
print_log.warn("log_path: ",g_log_directory)
print_log.error("log_path: ",g_log_directory,os.path)

猜你喜欢

转载自www.cnblogs.com/small-wei/p/11492633.html