当前位置:   article > 正文

python如何写日志_Python写日志文件

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]#

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/810491
推荐阅读
相关标签
  

闽ICP备14008679号