Skip to content

Commit

Permalink
Merge pull request #28 from saydigital/feature/logging
Browse files Browse the repository at this point in the history
[IMP] Add logging
  • Loading branch information
OpenCode authored May 16, 2022
2 parents 5fc27e8 + ba6f75e commit 5441151
Show file tree
Hide file tree
Showing 6 changed files with 129 additions and 1 deletion.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
fungiforme.ini
RULES.md
*.log
logs/

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
6 changes: 6 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@
- Configurable rules
- Check if an user remove a vote
- Add a medal on message based on position and configuration

## [1.0.1] - 2022-05-15

### Added

- logging
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.0
1.0.1
20 changes: 20 additions & 0 deletions fungiforme.ini.example
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,23 @@ DateFormat = %%Y-%%m-%%d
HourStart = 14:00:00
HourEnd = 15:00:00
TimezoneHoursDelay = 2

[LOGGING]
level = info
format = %%(asctime)s %%(process)d %%(levelname)s ? %%(name)s: %%(message)s
# if specified, a log file is used.
filepath = logs/fungiforme.log
# determines log rotation policy. possible values are: size, time
# If omitted but 'filepath' is specified, log file is not rotated.
# Omit this to handle log rotation with system tools like 'newsyslog' and 'logrotate'
logRotate = time
# If 'logRotate' is set to 'size', specify the max file width (in bytes) aftr that
# log file must be rotated
maxBytes = 100000000
# max number of rotated log files
backupCount = 10
# If 'logRotate' is set to 'time', specify when a file must be rotated.
# See https://docs.python.org/3.7/library/logging.handlers.html#timedrotatingfilehandler for possible values
when = D
# If 'logRotate' is set to 'time', specify rotation interval.
interval = 1
4 changes: 4 additions & 0 deletions fungiforme.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@
from datetime import datetime, timedelta
from discord.ext import commands
from discord import Embed, Color, File as DiscordFile
import logsetup
import logging


config = configparser.ConfigParser()
config.read('fungiforme.ini', encoding='UTF-8')

logsetup.setup(config)
logger = logging.getLogger('fungiforme')

TOKEN = config['DISCORD']['Token']
COMMAND_PREFIX = config['DISCORD']['CommandPrefix']
Expand Down
91 changes: 91 additions & 0 deletions logsetup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import logging
import os

from logging.handlers import WatchedFileHandler, RotatingFileHandler, TimedRotatingFileHandler
from datetime import datetime

DEFAULT_LEVEL = "INFO"
DEFAULT_FORMAT = r"%(asctime)s %(process)d %(levelname)s ? %(name)s: %(message)s"
DEFAULT_MAX_BYTES = 100000000
DEFAULT_BACKUP_COUNT = 10
DEFAULT_ROLLOVER_TIME = "00:00:00"
DEFAULT_WHEN = "D"
DEFAULT_INTERVAL = 1


def _set_console_logging():
logging.basicConfig(
level=getattr(logging, DEFAULT_LEVEL),
format=DEFAULT_FORMAT
)


def _set_file_logging(log_config):
log_filepath = log_config.get('filepath', '')
log_rotate = log_config.get('logRotate', '')
log_level = log_config.get('level', DEFAULT_LEVEL).upper()
log_format = log_config.get('format', DEFAULT_FORMAT)
log_handlers = []

os.makedirs(os.path.dirname(log_filepath), exist_ok=True)

if log_rotate == 'size':
max_bytes = log_config.getint('maxBytes', DEFAULT_MAX_BYTES)
backup_count = log_config.getint('backupCount', DEFAULT_BACKUP_COUNT)
log_file_handler = RotatingFileHandler(
log_filepath,
maxBytes=max_bytes,
backupCount=backup_count,
encoding='utf-8'
)
elif log_rotate == 'time':
rollover_time = log_config.get('rolloverTime', DEFAULT_ROLLOVER_TIME)
backup_count = log_config.getint('backupCount', DEFAULT_BACKUP_COUNT)
when = log_config.get('when', DEFAULT_WHEN)
interval = log_config.getint('interval', DEFAULT_INTERVAL)
if when == 'midnight':
at_time = None
else:
at_time = datetime.strptime(rollover_time, '%H:%M:%S')
log_file_handler = TimedRotatingFileHandler(
log_filepath,
when=when,
interval=interval,
atTime=at_time,
backupCount=backup_count,
encoding='utf-8'
)
else:
if os.name == 'posix':
# if fungiforme is running on Unix/Linux OS, we use WatchedFileHandler to allow
# usage of system tools like 'logrotate' to perform log rotation.
# WatchedFileHandler is not supported under Windows.
log_file_handler = WatchedFileHandler(log_filepath, encoding='utf-8')
else:
log_file_handler = logging.FileHandler(log_filepath, encoding='utf-8')

log_file_handler.setFormatter(logging.Formatter(log_format))
log_handlers.append(log_file_handler)

logging.basicConfig(
level=getattr(logging, log_level),
handlers=log_handlers
)


def setup(config):
if not config.has_section('LOGGING'):
_set_console_logging()
else:
log_config = config['LOGGING']
log_filepath = log_config.get('filepath', '')

if log_filepath:
_set_file_logging(log_config)
else:
log_level = log_config.get('level', DEFAULT_LEVEL).upper()
log_format = log_config.get('format', DEFAULT_FORMAT)
logging.basicConfig(
level=getattr(logging, log_level),
format=log_format
)

0 comments on commit 5441151

Please sign in to comment.