/usr/share/pyshared/ZConfig/components/logger/handlers.py is in python-zconfig 2.9.3-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""ZConfig factory datatypes for log handlers."""
import sys
from ZConfig.components.logger.factory import Factory
_log_format_variables = {
'name': '',
'levelno': '3',
'levelname': 'DEBUG',
'pathname': 'apath',
'filename': 'afile',
'module': 'amodule',
'lineno': 1,
'created': 1.1,
'asctime': 'atime',
'msecs': 1,
'relativeCreated': 1,
'thread': 1,
'message': 'amessage',
'process': 1,
}
def log_format(value):
value = ctrl_char_insert(value)
try:
# Make sure the format string uses only names that will be
# provided, and has reasonable type flags for each, and does
# not expect positional args.
value % _log_format_variables
except (ValueError, KeyError):
raise ValueError('Invalid log format string %s' % value)
return value
_control_char_rewrites = {r'\n': '\n', r'\t': '\t', r'\b': '\b',
r'\f': '\f', r'\r': '\r'}.items()
def ctrl_char_insert(value):
for pattern, replacement in _control_char_rewrites:
value = value.replace(pattern, replacement)
return value
def resolve(name):
"""Given a dotted name, returns an object imported from a Python module."""
name = name.split('.')
used = name.pop(0)
found = __import__(used)
for n in name:
used += '.' + n
try:
found = getattr(found, n)
except AttributeError:
__import__(used)
found = getattr(found, n)
return found
class HandlerFactory(Factory):
def __init__(self, section):
Factory.__init__(self)
self.section = section
def create_loghandler(self):
raise NotImplementedError(
"subclasses must override create_loghandler()")
def create(self):
import logging
logger = self.create_loghandler()
if self.section.formatter:
f = resolve(self.section.formatter)
else:
f = logging.Formatter
logger.setFormatter(f(self.section.format, self.section.dateformat))
logger.setLevel(self.section.level)
return logger
def getLevel(self):
return self.section.level
class FileHandlerFactory(HandlerFactory):
def create_loghandler(self):
from ZConfig.components.logger import loghandler
path = self.section.path
max_bytes = self.section.max_size
old_files = self.section.old_files
when = self.section.when
interval = self.section.interval
if path == "STDERR":
if max_bytes or old_files:
raise ValueError("cannot rotate STDERR")
handler = loghandler.StreamHandler(sys.stderr)
elif path == "STDOUT":
if max_bytes or old_files:
raise ValueError("cannot rotate STDOUT")
handler = loghandler.StreamHandler(sys.stdout)
elif when or max_bytes or old_files or interval:
if not old_files:
raise ValueError("old-files must be set for log rotation")
if when:
if max_bytes:
raise ValueError("can't set *both* max_bytes and when")
if not interval:
interval = 1
handler = loghandler.TimedRotatingFileHandler(
path, when=when, interval=interval,
backupCount=old_files)
elif max_bytes:
handler = loghandler.RotatingFileHandler(
path, maxBytes=max_bytes, backupCount=old_files)
else:
raise ValueError(
"max-bytes or when must be set for log rotation")
else:
handler = loghandler.FileHandler(path)
return handler
_syslog_facilities = {
"auth": 1,
"authpriv": 1,
"cron": 1,
"daemon": 1,
"kern": 1,
"lpr": 1,
"mail": 1,
"news": 1,
"security": 1,
"syslog": 1,
"user": 1,
"uucp": 1,
"local0": 1,
"local1": 1,
"local2": 1,
"local3": 1,
"local4": 1,
"local5": 1,
"local6": 1,
"local7": 1,
}
def syslog_facility(value):
value = value.lower()
if not _syslog_facilities.has_key(value):
L = _syslog_facilities.keys()
L.sort()
raise ValueError("Syslog facility must be one of " + ", ".join(L))
return value
class SyslogHandlerFactory(HandlerFactory):
def create_loghandler(self):
from ZConfig.components.logger import loghandler
return loghandler.SysLogHandler(self.section.address.address,
self.section.facility)
class Win32EventLogFactory(HandlerFactory):
def create_loghandler(self):
from ZConfig.components.logger import loghandler
return loghandler.Win32EventLogHandler(self.section.appname)
def http_handler_url(value):
import urlparse
scheme, netloc, path, param, query, fragment = urlparse.urlparse(value)
if scheme != 'http':
raise ValueError('url must be an http url')
if not netloc:
raise ValueError('url must specify a location')
if not path:
raise ValueError('url must specify a path')
q = []
if param:
q.append(';')
q.append(param)
if query:
q.append('?')
q.append(query)
if fragment:
q.append('#')
q.append(fragment)
return (netloc, path + ''.join(q))
def get_or_post(value):
value = value.upper()
if value not in ('GET', 'POST'):
raise ValueError('method must be "GET" or "POST", instead received: '
+ repr(value))
return value
class HTTPHandlerFactory(HandlerFactory):
def create_loghandler(self):
from ZConfig.components.logger import loghandler
host, selector = self.section.url
return loghandler.HTTPHandler(host, selector, self.section.method)
class SMTPHandlerFactory(HandlerFactory):
def create_loghandler(self):
from ZConfig.components.logger import loghandler
host, port = self.section.smtp_server
if not port:
mailhost = host
else:
mailhost = host, port
kwargs = {}
if self.section.smtp_username and self.section.smtp_password:
# Since credentials were only added in py2.6 we use a kwarg to not
# break compatibility with older py
if sys.version_info < (2, 6):
raise ValueError('SMTP auth requires at least Python 2.6.')
kwargs['credentials'] = (self.section.smtp_username,
self.section.smtp_password)
elif (self.section.smtp_username or self.section.smtp_password):
raise ValueError(
'Either both smtp-username and smtp-password or none must be '
'given')
return loghandler.SMTPHandler(mailhost,
self.section.fromaddr,
self.section.toaddrs,
self.section.subject,
**kwargs)
|