~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to start-loggerhead.py

  • Committer: Michael Hudson
  • Date: 2008-06-19 19:27:46 UTC
  • mto: This revision was merged to the branch mainline in revision 164.
  • Revision ID: michael.hudson@canonical.com-20080619192746-26f2iji413z5th33
add explicit import of logging.handlers

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python2.4
 
2
 
 
3
import logging
 
4
import logging.handlers
 
5
import os
 
6
import sys
 
7
from optparse import OptionParser
 
8
 
 
9
from loggerhead.apps.config import Root
 
10
from paste import httpserver
 
11
from paste.httpexceptions import make_middleware
 
12
from paste.translogger import make_filter
 
13
 
 
14
from loggerhead import daemon, release
 
15
 
 
16
 
 
17
def make_handler(config, filename):
 
18
    roll = config.get('log.roll', 'never')
 
19
    if roll == 'daily':
 
20
        h = logging.handlers.TimedRotatingFileHandler(filename, 'midnight', 0, 100)
 
21
    elif roll == 'weekly':
 
22
        h = logging.handlers.TimedRotatingFileHandler(filename, 'W0', 0, 100)
 
23
    else:
 
24
        h = logging.FileHandler(filename)
 
25
    return h
 
26
 
 
27
 
 
28
def setup_logging(home, config, foreground):
 
29
    # i hate that stupid logging config format, so just set up logging here.
 
30
 
 
31
    log_folder = os.path.join(home, 'logs')
 
32
    if not os.path.exists(log_folder):
 
33
        os.mkdir(log_folder)
 
34
 
 
35
    f = logging.Formatter('%(levelname)-.3s [%(asctime)s.%(msecs)03d] %(name)s: %(message)s',
 
36
                          '%Y%m%d-%H:%M:%S')
 
37
    debug_log = make_handler(config, os.path.join(log_folder, 'debug.log'))
 
38
    debug_log.setLevel(logging.DEBUG)
 
39
    debug_log.setFormatter(f)
 
40
    if foreground:
 
41
        stdout_log = logging.StreamHandler(sys.stdout)
 
42
        stdout_log.setLevel(logging.DEBUG)
 
43
        stdout_log.setFormatter(f)
 
44
    f = logging.Formatter('[%(asctime)s.%(msecs)03d] %(message)s',
 
45
                          '%Y%m%d-%H:%M:%S')
 
46
    access_log = make_handler(config, os.path.join(log_folder, 'access.log'))
 
47
    access_log.setLevel(logging.INFO)
 
48
    access_log.setFormatter(f)
 
49
 
 
50
    logging.getLogger('').addHandler(debug_log)
 
51
    logging.getLogger('turbogears.access').addHandler(access_log)
 
52
    logging.getLogger('turbogears.controllers').setLevel(logging.INFO)
 
53
 
 
54
    if foreground:
 
55
        logging.getLogger('').addHandler(stdout_log)
 
56
 
 
57
 
 
58
 
 
59
def main():
 
60
    parser = OptionParser(usage='usage: %prog [options]', version='%prog ' + release.version)
 
61
    parser.add_option('-f', '--foreground', action='store_true', dest='foreground', default=False,
 
62
                      help="run in the foreground; don't daemonize")
 
63
    parser.add_option('-C', '--check', action='store_true', dest='check', default=False,
 
64
                      help="only start if not already running (useful for cron jobs)")
 
65
    options, args = parser.parse_args()
 
66
    if len(args) > 0:
 
67
        parser.error('No filename arguments are used, only options.')
 
68
 
 
69
 
 
70
    home = os.path.realpath(os.path.dirname(__file__))
 
71
    pidfile = os.path.join(home, 'loggerhead.pid')
 
72
 
 
73
    if options.check:
 
74
        if daemon.is_running(pidfile):
 
75
            sys.exit(0)
 
76
        sys.stderr.write('Did not find loggerhead running in %r; restarting...\n' % (pidfile,))
 
77
 
 
78
    # read loggerhead config
 
79
 
 
80
    from configobj import ConfigObj
 
81
    config = ConfigObj(os.path.join(home, 'loggerhead.conf'), encoding='utf-8')
 
82
    extra_path = config.get('bzrpath', None)
 
83
    if extra_path:
 
84
        sys.path.insert(0, extra_path)
 
85
 
 
86
    #turbogears.update_config(configfile="dev.cfg", modulename="loggerhead.config")
 
87
 
 
88
    potential_overrides = [ ('server.socket_port', int),
 
89
                            ('server.webpath', str),
 
90
                            ('server.thread_pool', int),
 
91
                            ('server.socket_host' ,str) ]
 
92
    server_port = int(config.get('server.socket_port', 8080))
 
93
    nworkers = int(config.get('server.thread_pool', 10))
 
94
    server_host = config.get('server.socket_host', '0.0.0.0')
 
95
    webpath = config.get('server.webpath', None)
 
96
 
 
97
    for key, keytype in potential_overrides:
 
98
        value = config.get(key, None)
 
99
        if value is not None:
 
100
            value = keytype(value)
 
101
            #turbogears.config.update({ key: value })
 
102
 
 
103
    if not options.foreground:
 
104
        sys.stderr.write('\n')
 
105
        sys.stderr.write('Launching loggerhead into the background.\n')
 
106
        sys.stderr.write('PID file: %s\n' % (pidfile,))
 
107
        sys.stderr.write('\n')
 
108
 
 
109
        daemon.daemonize(pidfile, home)
 
110
 
 
111
    setup_logging(home, config, foreground=options.foreground)
 
112
 
 
113
    log = logging.getLogger('loggerhead')
 
114
    log.info('Starting up...')
 
115
 
 
116
    app = Root(config)
 
117
 
 
118
    app = app
 
119
    app = make_middleware(app)
 
120
    app = make_filter(app, None)
 
121
 
 
122
    if webpath:
 
123
        if not webpath.endswith('/'):
 
124
            webpath += '/'
 
125
        def app(environ, start_response, app=app):
 
126
            environ['SCRIPT_NAME'] = webpath
 
127
            return app(environ, start_response)
 
128
 
 
129
    try:
 
130
        httpserver.serve(
 
131
            app, host=server_host, port=server_port,
 
132
            threadpool_workers=nworkers)
 
133
    finally:
 
134
        log.info('Shutdown.')
 
135
        try:
 
136
            os.remove(pidfile)
 
137
        except OSError:
 
138
            pass
 
139
 
 
140
 
 
141
if __name__ == '__main__':
 
142
    main()