2011-12-11 27 views
40

bất cứ ai có thể đề xuất một cách trong python để làm đăng nhập với:Python, muốn đăng nhập với luân log và nén

xoay
  • log mỗi ngày
  • nén của các bản ghi khi họ đang xoay
  • tùy chọn - xóa log file lâu đời nhất để giữ gìn X MB dung lượng miễn phí
  • tùy chọn - file sftp log vào máy chủ

Thanks cho bất kỳ phản ứng, Fred

+0

Rotation? Bạn có nghĩa là chạy kịch bản mỗi ngày? Nếu vậy, tôi đề nghị sử dụng một công việc cron. – Griffin

+0

Ứng dụng của tôi sẽ chạy và ghi nhật ký liên tục, vì vậy tôi muốn hệ thống bắt đầu một tệp nhật ký mới mỗi ngày –

+2

liên quan [Vấn đề Python 13516: Tệp nhật ký cũ Gzip trong trình xử lý xoay] (http://bugs.python.org/issue13516) đề cập đến [ví dụ TimedCompressedRotatingFileHandler] (http://code.activestate.com/recipes/502265-timedcompressedrotatingfilehandler/) – jfs

Trả lời

57
  • log xoay mỗi ngày: Sử dụng một nén TimedRotatingFileHandler
  • gỗ: Thiết lập các tham số encoding='bz2'. (Lưu ý "thủ thuật" này sẽ chỉ hoạt động đối với Python2. 'Bz2' không còn được coi là mã hóa trong Python3 nữa.)
  • tùy chọn - xóa tệp nhật ký cũ nhất để giữ lại dung lượng trống của MB là. Bạn có thể (gián tiếp) sắp xếp việc này bằng cách sử dụng RotatingFileHandler. Bằng cách đặt tham số maxBytes, tệp nhật ký sẽ di chuột qua khi nó đạt đến kích thước nhất định. Bằng cách đặt tham số backupCount, bạn có thể kiểm soát số lượng rollover được giữ. Hai thông số cùng nhau cho phép bạn kiểm soát không gian tối đa được tiêu thụ bởi các tệp nhật ký. Bạn có thể phân lớp TimeRotatingFileHandler để kết hợp hành vi này vào nó.

Chỉ cần cho vui, đây là cách bạn có thể phân lớp TimeRotatingFileHandler. Khi bạn chạy tập lệnh bên dưới, tệp sẽ ghi các tệp nhật ký vào /tmp/log_rotate*.

Với một giá trị nhỏ cho time.sleep (chẳng hạn như 0,1), tệp nhật ký sẽ điền nhanh, đạt giới hạn maxBytes và sau đó được cuộn qua.

Với số lớn time.sleep (chẳng hạn như 1.0), tệp nhật ký điền vào chậm, giới hạn maxBytes không được tiếp cận, nhưng chúng vẫn cuộn qua khi khoảng thời gian đã định thời gian (10 giây) đạt được.

Tất cả mã bên dưới là từ logging/handlers.py. Tôi chỉ đơn giản là lưới TimeRotatingFileHandler với RotatingFileHandler theo cách thẳng nhất có thể.

import time 
import re 
import os 
import stat 
import logging 
import logging.handlers as handlers 


class SizedTimedRotatingFileHandler(handlers.TimedRotatingFileHandler): 
    """ 
    Handler for logging to a set of files, which switches from one file 
    to the next when the current file reaches a certain size, or at certain 
    timed intervals 
    """ 

    def __init__(self, filename, maxBytes=0, backupCount=0, encoding=None, 
       delay=0, when='h', interval=1, utc=False): 
     handlers.TimedRotatingFileHandler.__init__(
      self, filename, when, interval, backupCount, encoding, delay, utc) 
     self.maxBytes = maxBytes 

    def shouldRollover(self, record): 
     """ 
     Determine if rollover should occur. 

     Basically, see if the supplied record would cause the file to exceed 
     the size limit we have. 
     """ 
     if self.stream is None:     # delay was set... 
      self.stream = self._open() 
     if self.maxBytes > 0:     # are we rolling over? 
      msg = "%s\n" % self.format(record) 
      # due to non-posix-compliant Windows feature 
      self.stream.seek(0, 2) 
      if self.stream.tell() + len(msg) >= self.maxBytes: 
       return 1 
     t = int(time.time()) 
     if t >= self.rolloverAt: 
      return 1 
     return 0 


def demo_SizedTimedRotatingFileHandler(): 
    log_filename = '/tmp/log_rotate' 
    logger = logging.getLogger('MyLogger') 
    logger.setLevel(logging.DEBUG) 
    handler = SizedTimedRotatingFileHandler(
     log_filename, maxBytes=100, backupCount=5, 
     when='s', interval=10, 
     # encoding='bz2', # uncomment for bz2 compression 
    ) 
    logger.addHandler(handler) 
    for i in range(10000): 
     time.sleep(0.1) 
     logger.debug('i=%d' % i) 

demo_SizedTimedRotatingFileHandler() 
+0

Cảm ơn, câu trả lời tuyệt vời –

+0

Những điều tốt nhất được thực hiện chỉ để cho vui! Thanks –

+0

Tham số 'mode' trong' __init __() 'được gán nhưng không bao giờ được sử dụng. – mshsayem

10

Ngoài câu trả lời của unutbu: dưới đây là cách sửa đổi TimedRotatingFileHandler để nén bằng tệp zip.

import logging 
import logging.handlers 
import zipfile 
import codecs 
import sys 
import os 
import time 
import glob 


class TimedCompressedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): 
    """ 
    Extended version of TimedRotatingFileHandler that compress logs on rollover. 
    """ 
    def doRollover(self): 
     """ 
     do a rollover; in this case, a date/time stamp is appended to the filename 
     when the rollover happens. However, you want the file to be named for the 
     start of the interval, not the current time. If there is a backup count, 
     then we have to get a list of matching filenames, sort them and remove 
     the one with the oldest suffix. 
     """ 

     self.stream.close() 
     # get the time that this sequence started at and make it a TimeTuple 
     t = self.rolloverAt - self.interval 
     timeTuple = time.localtime(t) 
     dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) 
     if os.path.exists(dfn): 
      os.remove(dfn) 
     os.rename(self.baseFilename, dfn) 
     if self.backupCount > 0: 
      # find the oldest log file and delete it 
      s = glob.glob(self.baseFilename + ".20*") 
      if len(s) > self.backupCount: 
       s.sort() 
       os.remove(s[0]) 
     #print "%s -> %s" % (self.baseFilename, dfn) 
     if self.encoding: 
      self.stream = codecs.open(self.baseFilename, 'w', self.encoding) 
     else: 
      self.stream = open(self.baseFilename, 'w') 
     self.rolloverAt = self.rolloverAt + self.interval 
     if os.path.exists(dfn + ".zip"): 
      os.remove(dfn + ".zip") 
     file = zipfile.ZipFile(dfn + ".zip", "w") 
     file.write(dfn, os.path.basename(dfn), zipfile.ZIP_DEFLATED) 
     file.close() 
     os.remove(dfn) 
11

Một cách khác để nén logfile trong xoay (mới trong python 3.3) đang sử dụng BaseRotatingHandler (và tất cả được thừa kế) thuộc tính lớp rotator ví dụ:

import gzip 
import os 
import logging 
import logging.handlers 

class GZipRotator: 
    def __call__(self, source, dest): 
     os.rename(source, dest) 
     f_in = open(dest, 'rb') 
     f_out = gzip.open("%s.gz" % dest, 'wb') 
     f_out.writelines(f_in) 
     f_out.close() 
     f_in.close() 
     os.remove(dest) 

logformatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s') 
log = logging.handlers.TimedRotatingFileHandler('debug.log', 'midnight', 1, backupCount=5) 
log.setLevel(logging.DEBUG) 
log.setFormatter(logformatter) 
log.rotator = GZipRotator() 

logger = logging.getLogger('main') 
logger.addHandler(log)  
logger.setLevel(logging.DEBUG) 

.... 

hơn bạn có thể nhìn thấy here.

+2

Mẫu từ [nhật ký nấu ăn] (https://docs.python.org/3/howto/logging-cookbook.html#using-a-rotator-and-namer-to-customize-log-rotation-processing) là IMHO một chút sạch hơn, tách việc đổi tên từ nén (nhưng 1 cho con trỏ) – eddygeek

0

Để sao chép các tập tin, gzip tập tin sao chép (sử dụng thời gian kỷ nguyên), và sau đó giải phóng ra các file đã tồn tại trong một cách mà sẽ không phá vỡ các mô-đun logging:

import gzip 
import logging 
import os 
from shutil import copy2 
from time import time 

def logRoll(logfile_name): 
    log_backup_name = logfile_name + '.' + str(int(time())) 
    try: 
     copy2(logfile_name, log_backup_name) 
    except IOError, err: 
     logging.debug(' No logfile to roll') 
     return 
    f_in = open(log_backup_name, 'rb') 
    f_out = gzip.open(log_backup_name + '.gz', 'wb') 
    f_out.writelines(f_in) 
    f_out.close() 
    f_in.close() 
    os.remove(log_backup_name) 
    f=open(logfile_name, 'w') 
    f.close() 
2

Tôi đoán đó là quá muộn tham gia bữa tiệc, nhưng đây là những gì tôi đã làm. Tôi đã tạo một lớp mới kế thừa lớp logging.handlers.RotatingFileHandler và thêm một vài dòng để nén tệp trước khi di chuyển tệp.

https://github.com/rkreddy46/python_code_reference/blob/master/compressed_log_rotator.py

#!/usr/bin/env python 

# Import all the needed modules 
import logging.handlers 
import sys 
import time 
import gzip 
import os 
import shutil 
import random 
import string 

__version__ = 1.0 
__descr__ = "This logic is written keeping in mind UNIX/LINUX/OSX platforms only" 


# Create a new class that inherits from RotatingFileHandler. This is where we add the new feature to compress the logs 
class CompressedRotatingFileHandler(logging.handlers.RotatingFileHandler): 
    def doRollover(self): 
     """ 
     Do a rollover, as described in __init__(). 
     """ 
     if self.stream: 
      self.stream.close() 
     if self.backupCount > 0: 
      for i in range(self.backupCount - 1, 0, -1): 
       sfn = "%s.%d.gz" % (self.baseFilename, i) 
       dfn = "%s.%d.gz" % (self.baseFilename, i + 1) 
       if os.path.exists(sfn): 
        # print "%s -> %s" % (sfn, dfn) 
        if os.path.exists(dfn): 
         os.remove(dfn) 
        os.rename(sfn, dfn) 
      dfn = self.baseFilename + ".1.gz" 
      if os.path.exists(dfn): 
       os.remove(dfn) 
      # These two lines below are the only new lines. I commented out the os.rename(self.baseFilename, dfn) and 
      # replaced it with these two lines. 
      with open(self.baseFilename, 'rb') as f_in, gzip.open(dfn, 'wb') as f_out: 
       shutil.copyfileobj(f_in, f_out) 
      # os.rename(self.baseFilename, dfn) 
      # print "%s -> %s" % (self.baseFilename, dfn) 
     self.mode = 'w' 
     self.stream = self._open() 

# Specify which file will be used for our logs 
log_filename = "/Users/myname/Downloads/test_logs/sample_log.txt" 

# Create a logger instance and set the facility level 
my_logger = logging.getLogger() 
my_logger.setLevel(logging.DEBUG) 

# Create a handler using our new class that rotates and compresses 
file_handler = CompressedRotatingFileHandler(filename=log_filename, maxBytes=1000000, backupCount=10) 

# Create a stream handler that shows the same log on the terminal (just for debug purposes) 
view_handler = logging.StreamHandler(stream=sys.stdout) 

# Add all the handlers to the logging instance 
my_logger.addHandler(file_handler) 
my_logger.addHandler(view_handler) 

# This is optional to beef up the logs 
random_huge_data = "".join(random.choice(string.ascii_letters) for _ in xrange(10000)) 

# All this code is user-specific, write your own code if you want to play around 
count = 0 
while True: 
    my_logger.debug("This is the message number %s" % str(count)) 
    my_logger.debug(random_huge_data) 
    count += 1 
    if count % 100 == 0: 
     count = 0 
     time.sleep(2) 
0

Tôi nghĩ rằng lựa chọn tốt nhất sẽ được sử dụng thực hiện hiện tại của TimedRotatingFileHandler và sau khi đổi tên file log lên phiên bản xoay chỉ nén nó:

import zipfile 
import os 
from logging.handlers import TimedRotatingFileHandler 


class TimedCompressedRotatingFileHandler(TimedRotatingFileHandler): 
    """ 
    Extended version of TimedRotatingFileHandler that compress logs on rollover. 
    """ 
    def find_last_rotated_file(self): 
     dir_name, base_name = os.path.split(self.baseFilename) 
     file_names = os.listdir(dir_name) 
     result = [] 
     prefix = '{}.20'.format(base_name) # we want to find a rotated file with eg filename.2017-12-12... name 
     for file_name in file_names: 
      if file_name.startswith(prefix) and not file_name.endswith('.zip'): 
       result.append(file_name) 
     result.sort() 
     return result[0] 

    def doRollover(self): 
     super(TimedCompressedRotatingFileHandler, self).doRollover() 

     dfn = self.find_last_rotated_file() 
     dfn_zipped = '{}.zip'.format(dfn) 
     if os.path.exists(dfn_zipped): 
      os.remove(dfn_zipped) 
     with zipfile.ZipFile(dfn_zipped, 'w') as f: 
      f.write(dfn, dfn_zipped, zipfile.ZIP_DEFLATED) 
     os.remove(dfn) 
Các vấn đề liên quan