1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-01-08 21:18:00 +03:00

Unified "NotificationLevel" with "LogLevel" (in fact, same meaning)

This commit is contained in:
Adolfo Gómez García 2023-04-21 00:25:54 +02:00
parent 5eb058e44a
commit a75e250aeb
No known key found for this signature in database
GPG Key ID: DD1ABF20724CDA23
7 changed files with 26 additions and 35 deletions

View File

@ -35,11 +35,10 @@ import typing
from django.utils.translation import gettext_lazy as _, gettext
from uds.core.environment import Environment
from uds.models import Notifier, NotificationLevel
from uds.models import Notifier, LogLevel
from uds.core import messaging
from uds.core.ui import gui
from uds.core.util import permissions
from uds.core.managers import notifications
from uds.REST.model import ModelHandler
@ -86,7 +85,7 @@ class Notifiers(ModelHandler):
for field in [
{
'name': 'level',
'values': [gui.choiceItem(i[0], i[1]) for i in NotificationLevel.all()],
'values': [gui.choiceItem(i[0], i[1]) for i in LogLevel.all()],
'label': gettext('Level'),
'tooltip': gettext('Level of notifications'),
'type': gui.InputField.Types.CHOICE,

View File

@ -33,7 +33,7 @@ import logging
import typing
from uds.core.util import singleton
from uds.models.notifications import Notification, NotificationLevel
from uds.models.notifications import Notification, LogLevel
if typing.TYPE_CHECKING:
from ..messaging import provider
@ -59,7 +59,7 @@ class NotificationsManager(metaclass=singleton.Singleton):
self,
group: str,
identificator: str,
level: NotificationLevel,
level: LogLevel,
message: str,
*args
) -> None:

View File

@ -146,7 +146,7 @@ class TaskManager(metaclass=singleton.Singleton):
self.threads.append(thread)
time.sleep(0.5) # Wait a bit before next delayed task runner is started
# Add other tasks
# Add any other tasks (Such as message processor)
self.addOtherTasks()
# Debugging stuff

View File

@ -47,7 +47,9 @@ useLogger = logging.getLogger('useLog')
# Patter for look for date and time in this format: 2023-04-20 04:03:08,776 (and trailing spaces)
# This is the format used by python logging module
DATETIME_PATTERN: typing.Final[re.Pattern] = re.compile(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) *')
DATETIME_PATTERN: typing.Final[re.Pattern] = re.compile(
r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) *'
)
class LogLevel(enum.IntEnum):
@ -82,6 +84,11 @@ class LogLevel(enum.IntEnum):
except ValueError:
return cls.OTHER
# Return all Log levels as tuples of (level value, level name)
@staticmethod
def all() -> typing.List[typing.Tuple[int, str]]:
return [(level.value, level.name) for level in LogLevel]
class LogSource(enum.StrEnum):
INTERNAL = 'internal'
@ -183,20 +190,21 @@ class UDSLogHandler(logging.handlers.RotatingFileHandler):
emiting: typing.ClassVar[bool] = False
def emit(self, record: logging.LogRecord) -> None:
# To avoid circular imports
# pylint: disable=import-outside-toplevel
from uds.core.managers.notifications import NotificationsManager
if apps.ready and record.levelno >= logging.INFO and not UDSLogHandler.emiting:
try:
logLevel = LogLevel.fromInt(record.levelno * 1000)
UDSLogHandler.emiting = True
msg = self.format(record)
# Remove date and time from message, as it will be stored on database
msg = DATETIME_PATTERN.sub('', msg)
doLog(
None,
LogLevel.fromInt(record.levelno * 1000),
msg,
LogSource.LOGS,
False,
os.path.basename(self.baseFilename)
)
identificator = os.path.basename(self.baseFilename)
if record.levelno >= logging.WARNING:
NotificationsManager().notify('log', identificator, logLevel, msg)
doLog(None, logLevel, msg, LogSource.LOGS, False, identificator)
except Exception: # nosec: If cannot log, just ignore it
pass
finally:

View File

@ -97,7 +97,7 @@ class Migration(migrations.Migration):
(
"level",
models.PositiveSmallIntegerField(
default=uds.models.notifications.NotificationLevel["ERROR"]
default=uds.models.notifications.LogLevel["ERROR"]
),
),
],

View File

@ -111,7 +111,7 @@ from .actor_token import ActorToken
from .tunnel_token import TunnelToken
# Notifications & Alerts
from .notifications import Notification, Notifier, NotificationLevel
from .notifications import Notification, Notifier, LogLevel
# Multi factor authentication
from .mfa import MFA

View File

@ -28,12 +28,12 @@
"""
Author: Adolfo Gómez, dkmaster at dkmon dot com
"""
from enum import IntEnum
import logging
import typing
from django.db import models, transaction
from uds.core.util.log import LogLevel
from .managed_object_model import ManagedObjectModel
from .tag import TaggingMixin
@ -44,22 +44,6 @@ if typing.TYPE_CHECKING:
from uds.core.messaging import Notifier as NotificationProviderModule
class NotificationLevel(IntEnum):
"""
Notification Levels
"""
INFO = 0
WARNING = 1
ERROR = 2
CRITICAL = 3
# Return all notification levels as tuples of (level value, level name)
@staticmethod
def all() -> typing.List[typing.Tuple[int, str]]:
return [(level.value, level.name) for level in NotificationLevel]
# This model will be available on local "persistent" storage and also on configured database
class Notification(models.Model):
stamp = models.DateTimeField(auto_now_add=True)
@ -103,7 +87,7 @@ class Notifier(ManagedObjectModel, TaggingMixin):
name = models.CharField(max_length=128, default='')
comments = models.CharField(max_length=256, default='')
enabled = models.BooleanField(default=True)
level = models.PositiveSmallIntegerField(default=NotificationLevel.ERROR)
level = models.PositiveSmallIntegerField(default=LogLevel.ERROR)
# "fake" declarations for type checking
objects: 'models.manager.Manager[Notifier]'