Python 实现写日志文件

【例】/root/testpmpy/bin/recordLog.py的作用是记录日志,记录的日志会存放在/root/testpmpy/log下。最新的日志名称为iamrecord.log,之后每次运行都会将上一个iamrecord.log加上时间戳后缀。recordLog.py内容如下

注:举例仅描述功能,单独使用没有实际意义,可以作为函数嵌入到其它脚本。

import sys, os, time, shutil
import datetime as pydate

root_dir = os.path.dirname(os.path.abspath(__file__)).split('bin')[0]
logfile = None
currentlog = None

def startLog():
    global logfile, currentlog
    try:
        logdir = root_dir + os.sep + 'log'
        if not os.path.exists(logdir):
            os.makedirs(logdir)
        currentlog = logdir + os.sep + "iamrecord" + ".log"

        if(os.path.isfile(currentlog)):
            logtime = pydate.datetime.now().strftime("%Y-%m-%d_%H.%M.%S")
            historylog = currentlog + "." + logtime
            #将上一个iamrecord复制为加上时间戳的iamrecord.log.yyyy-mm-dd_HH.MM.SS
            shutil.copyfile(currentlog, historylog)

        logfile = open(currentlog, 'w')

    except Exception as e:
        print(str(e))

    writeLog("Start to log:")
    print("Start to log:")

def stopLog():
    global logfile
    try:
        time.sleep(0.1)
        writeLog("Finish the log.")
        logfile.close()
        print("Finish the log.")

    except Exception as e:
        print(str(e))

def writeLog(str):
    global logfile
    timeStamp = pydate.datetime.now().strftime("%Y-%m-%d %H.%M.%S.%f")
    logfile.write(timeStamp + "\t" + str + "\n")
    logfile.flush()

def test_today():
    #只写日志、不输出到屏幕上
    writeLog("Today is Tuesday.")
    writeLog("Today is a sunny day.")

def test_cpfile(src_file,tgt_file):

    if(os.path.exists(src_file)):
        msg = "Copy file from '" + src_file + "' to '" + tgt_file + "'."
        #写日志、同时也印到屏幕上
        print(msg)
        writeLog(msg)
        shutil.copyfile(src_file, tgt_file)
    else:
        msg = src_file + " not existed."
        print(msg)
        writeLog(msg)

if __name__ == '__main__':

    startLog()
    test_today()
    test_cpfile('/root/testpmpy/user_op_log.1','/tmp/tmplog')
    stopLog()

说明:
line4,os.path.abspath(__file__) -> 获取当前脚本的完整路径,recordLog.py所在的路径是/bin/, 紧接着.split('bin')[0] -> 以"bin"为分隔符,得到路径/root/testpmpy
line10 ,os.path.exists()判断括号中的文件是否存在

执行recordLog.py输出如下,注意 test_today() 和 test_cpfile() 的差别 -> 打印到屏幕和写入日志文件:

[root@xxx bin]# python3 recordLog.py
Start to log:
Copy file from '/root/testpmpy/user_op_log.1' to '/tmp/tmplog'.
Finish the log.
[root@xxx bin]# cd ../log/
[root@xxx log]# ls -l
total 16
-rw-r--r--. 1 root root 269 Mar 17 17:51 iamrecord.log
-rw-r--r--. 1 root root 269 Mar 17 17:42 iamrecord.log.2020-03-17_17.42.38
-rw-r--r--. 1 root root 269 Mar 17 17:47 iamrecord.log.2020-03-17_17.47.18
-rw-r--r--. 1 root root   0 Mar 17 17:49 iamrecord.log.2020-03-17_17.49.47
-rw-r--r--. 1 root root 269 Mar 17 17:51 iamrecord.log.2020-03-17_17.51.43
[root@xxx log]# cat iamrecord.log
2020-03-17 17.51.43.927020      Start to log:
2020-03-17 17.51.43.927112      Today is Tuesday.
2020-03-17 17.51.43.927161      Today is a sunny day.
2020-03-17 17.51.43.927233      Copy file from '/root/testpmpy/user_op_log.1' to '/tmp/tmplog'.
2020-03-17 17.51.44.027720      Finish the log.
[root@xxx log]#

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值