| 1 |
""" |
| 2 |
Helper code for logging to files. |
| 3 |
|
| 4 |
All logs that could be used both interactively and from the web server |
| 5 |
but have group ownership gavo and mode (at least) 664. Only then can |
| 6 |
both parties write logs. |
| 7 |
|
| 8 |
The RotatingFileHandler in this module tries to ensure this. |
| 9 |
""" |
| 10 |
|
| 11 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 12 |
#c |
| 13 |
#c This program is free software, covered by the GNU GPL. See the |
| 14 |
#c COPYING file in the source distribution. |
| 15 |
|
| 16 |
|
| 17 |
import grp |
| 18 |
import os |
| 19 |
import warnings |
| 20 |
import logging |
| 21 |
from logging import handlers |
| 22 |
|
| 23 |
from gavo import base |
| 24 |
|
| 25 |
|
| 26 |
try: |
| 27 |
GAVO_GROUP_ID = grp.getgrnam(base.getConfig("group"))[2] |
| 28 |
except KeyError: |
| 29 |
warnings.warn("Cannot figure out id of group '%s'. Logging will break.") |
| 30 |
GAVO_GROUP_ID = -1 |
| 31 |
|
| 32 |
|
| 33 |
class RotatingFileHandler(handlers.RotatingFileHandler): |
| 34 |
"""logging.handler.RotatingFile with forced group support. |
| 35 |
""" |
| 36 |
def __init__(self, *args, **kwargs): |
| 37 |
handlers.RotatingFileHandler.__init__(self, *args, **kwargs) |
| 38 |
self._setOwnership() |
| 39 |
|
| 40 |
def _setOwnership(self): |
| 41 |
# This will fail if we don't own the file. This doesn't hurt as long |
| 42 |
# as whoever created the file already fixed the permission |
| 43 |
try: |
| 44 |
os.chmod(self.stream.name, 0o664) |
| 45 |
os.chown(self.stream.name, -1, GAVO_GROUP_ID) |
| 46 |
except os.error: # don't worry, see above |
| 47 |
pass |
| 48 |
|
| 49 |
def doRollover(self): |
| 50 |
handlers.RotatingFileHandler.doRollover(self) |
| 51 |
self._setOwnership() |
| 52 |
|
| 53 |
|
| 54 |
def getLoggingHandler(destName, |
| 55 |
purpose, |
| 56 |
maxBytes=500000, |
| 57 |
backupCount=3, |
| 58 |
mode=0o664): |
| 59 |
"""returns a RotatingFileHandler for logging writing to destName. |
| 60 |
|
| 61 |
If destName is not writable, then a plain StreamLogger is |
| 62 |
returned. |
| 63 |
""" |
| 64 |
try: |
| 65 |
return RotatingFileHandler(destName, |
| 66 |
maxBytes=maxBytes, |
| 67 |
backupCount=backupCount, |
| 68 |
mode=mode, |
| 69 |
encoding="utf-8") |
| 70 |
except os.error: |
| 71 |
warnings.warn(f"Cannot write to {destName}, using stderr for {purpose}." |
| 72 |
" Perhaps add yourself to the gavo group?") |
| 73 |
return logging.StreamHandler() |