logging.py 2.5 KB
Newer Older
1 2
#!/usr/bin/env python

J
James Troup 已提交
3
# Logging functions
J
James Troup 已提交
4
# Copyright (C) 2001, 2002  James Troup <james@nocrew.org>
5
# $Id: logging.py,v 1.4 2005-11-15 09:50:32 ajt Exp $
J
James Troup 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
J
James Troup 已提交
20

J
James Troup 已提交
21 22
################################################################################

23
import os, pwd, time, sys;
24
import utils;
J
James Troup 已提交
25 26 27 28 29 30 31 32 33

################################################################################

class Logger:
    "Logger object"
    Cnf = None;
    logfile = None;
    program = None;

34
    def __init__ (self, Cnf, program, debug=0):
J
James Troup 已提交
35 36 37 38
        "Initialize a new Logger object"
        self.Cnf = Cnf;
        self.program = program;
        # Create the log directory if it doesn't exist
J
James Troup 已提交
39
        logdir = Cnf["Dir::Log"];
J
James Troup 已提交
40 41 42 43
        if not os.path.exists(logdir):
            umask = os.umask(00000);
            os.makedirs(logdir, 02775);
        # Open the logfile
44
        logfilename = "%s/%s" % (logdir, time.strftime("%Y-%m"));
45 46 47 48 49
	logfile = None
	if debug:
	    logfile = sys.stderr
	else:
	    logfile = utils.open_file(logfilename, 'a');
J
James Troup 已提交
50 51 52 53 54 55 56 57 58
        self.logfile = logfile;
        # Log the start of the program
        user = pwd.getpwuid(os.getuid())[0];
        self.log(["program start", user]);

    def log (self, details):
        "Log an event"
        # Prepend the timestamp and program name
        details.insert(0, self.program);
59
        timestamp = time.strftime("%Y%m%d%H%M%S");
J
James Troup 已提交
60 61 62 63
        details.insert(0, timestamp);
        # Force the contents of the list to be string.join-able
        details = map(str, details);
        # Write out the log in TSV
64
        self.logfile.write("|".join(details)+'\n');
J
James Troup 已提交
65 66 67 68 69 70 71 72
        # Flush the output to enable tail-ing
        self.logfile.flush();

    def close (self):
        "Close a Logger object"
        self.log(["program end"]);
        self.logfile.flush();
        self.logfile.close();