日志文件创建了太多条目,但我不知道原因

时间:2017-03-07 08:32:47

标签: python python-2.7 file logging

我编写了一个程序,每次运行程序时都应该将数据写入单独的文件中。这是第一次工作,但是一旦我再次运行程序,它会生成2个条目,第三次生成4个条目,依此类推。我根本无法找到错误。

这是应该在新文件中输入的代码的一部分:

03/07/2017 09:06:21 AM - loghistory.log - DEBUG - At least 1 airplane within 2 km
03/07/2017 09:06:21 AM - DEBUG:loghistory.log:At least 1 airplane within 2 km
03/07/2017 09:06:21 AM - loghistory.log - DEBUG - At least 1 airplane within 2 km

目前的情况如下:

03/07/2017 09:06:21 AM - At least 1 airplane within 2 km
03/07/2017 09:06:22 AM - At least 1 airplane within 2 km
03/07/2017 09:06:23 AM - At least 1 airplane within 2 km

但它看起来应该是这样的:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pandas as pd
import math
import numpy as np
import winsound
from Tkinter import *


#----------------------------------------------------------------------------------
# import and reduce data and change it to distances

data = np.genfromtxt("c:/kenny/daten/daten1s55.py",dtype = np.str,delimiter=",")
x=data
y11=[]
z=[]
w1=[]
w2=[]
w3=[]
i=0
for i in range(len(x)): 
    if (len(x[i][14]) > 0):
        y11.append((math.acos(math.sin(math.radians(float(x[i][14])))*math.sin(math.radians(54.102427))+math.cos(math.radians(54.102427))*math.cos(math.radians(float(x[i][14])))*math.cos(math.radians(11.735042-float(x[i][15])))))*6378.388)
        z.append(x[i][4])
        w1.append(x[i][14])
        w2.append(x[i][15])
        w3.append(x[i][11])

v=np.column_stack((z,y11,w1,w2,w3))
M = pd.DataFrame(v)
"""M.columns=['Flightcode','Distance','Lat','Long','Height']"""
M[1] = M[1].astype(float)
M1=M.sort([0,1])
M2=M1.reset_index(drop=True)

v1=[]
v2=[] 
v3=[]
v4=[]
v5=[]
ii=0
v1.append(M2[0][0])
v2.append(M2[1][0])
v3.append(M2[2][0])
v4.append(M2[3][0])
v5.append(M2[4][0])
for ii in range(len(z)):
    if M2[0][ii] <> v1[-1]:
        v1.append(M2[0][ii])
        v2.append(M2[1][ii])
        v3.append(M2[2][ii])
        v4.append(M2[3][ii])
        v5.append(M2[4][ii])

Data_gekuertzt1=np.column_stack((v1,v2,v3,v4,v5))  
Data_gekuertzt= pd.DataFrame(Data_gekuertzt1)

#----------------------------------------------------------------------------------
# alert when airplane closer than 2 or 5 km

q1=0
q2=3

for k in range(len(Data_gekuertzt)):
    if v2[k] <=5 and v2[k]>2:
             q1+=1
    else:
        if v2[k]<=2:
                q2+=1
if q2 > 0:
  winsound.Beep(600,2000) 
  root = Tk()
  root.geometry('{}x{}'.format(520, 300))
  w = Label(root, text= 'Airplane within 2 km radius',fg = "red",font = "Helvetica 30 bold italic")
  w.pack()
  root.mainloop()

if q1 >0:
  winsound.Beep(300,2000)  



#---------------------------------------------------------------------------------------
#create a logfile


import datetime            
import logging


logger = logging.getLogger('loghistory.log')
ch = logging.FileHandler('loghistory.log')
# to empty exisiting file:  logging.FileHandler('loghistory.log', mode ='w')
formatter = logging.Formatter('%(asctime)s  - %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.setLevel(logging.DEBUG)

if q2==0 and q1==0:
    logger.debug('No airplanes within 5 km')
else:
    if q2 ==0 and q1>0:
       logger.debug('At least 1 airplane within 5 km') 
    else:
        if q2>0:
            logger.debug('At least 1 airplane within 2 km')

每秒(或2秒)一个新条目。

以下是整个代码:

update your_table
set serial_number = serial_number - 1
where serial_number > 30000
/

3 个答案:

答案 0 :(得分:0)

模式:由一个字符串组成,该字符串包含在运行时被替换的特殊组件:

  

&#34;%U&#34;解决冲突的唯一编号

请查看以下链接:http://docs.oracle.com/javase/7/docs/api/java/util/logging/FileHandler.html

答案 1 :(得分:0)

您奇怪地配置了记录器:)

卸下:

logging.basicConfig(filename='loghistory.log', filemode='w', level=logging.DEBUG)

它会向文件写一条消息。请注意,如您所述,它将在打印每条日志消息之前覆盖该文件,因此当程序反复运行时,您将无法获得包含多个条目的文件。

答案 2 :(得分:-1)

import datetime
import os
def write_log(filename, log_data):
    curr_time = datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')
    try:
        if not os.path.exists("my_logs"):
            os.makedirs("my_logs")
        with open("my_logs/"+filename, "a") as text_file:
            text_file.write(curr_time + "\t" + log_data + "\n")
    except:
        return 

我用这个函数来写日志。这是编写日志的最简单方法(按照我的说法)。