mirror of
https://github.com/thingsboard/thingsboard-gateway
synced 2025-10-26 22:31:42 +08:00
60 lines
2.4 KiB
Python
60 lines
2.4 KiB
Python
# Copyright 2020. ThingsBoard
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import logging
|
|
import logging.handlers
|
|
|
|
|
|
class TBLoggerHandler(logging.Handler):
|
|
def __init__(self, gateway):
|
|
self.current_log_level = 'NOTSET'
|
|
super().__init__(logging.getLevelName(self.current_log_level))
|
|
self.__gateway = gateway
|
|
self.activated = False
|
|
self.loggers = ['service',
|
|
'storage',
|
|
'extension',
|
|
'connector',
|
|
'tb_connection'
|
|
]
|
|
for logger in self.loggers:
|
|
log = logging.getLogger(logger)
|
|
log.addHandler(self.__gateway.main_handler)
|
|
log.debug("Added remote handler to log %s", logger)
|
|
|
|
def activate(self, log_level=None):
|
|
try:
|
|
for logger in self.loggers:
|
|
if log_level is not None and logging.getLevelName(log_level) is not None:
|
|
if logger == 'tb_connection' and log_level == 'DEBUG':
|
|
log = logging.getLogger(logger)
|
|
log.setLevel(logging.getLevelName('INFO'))
|
|
else:
|
|
log = logging.getLogger(logger)
|
|
self.current_log_level = log_level
|
|
log.setLevel(logging.getLevelName(log_level))
|
|
except Exception as e:
|
|
log = logging.getLogger('service')
|
|
log.exception(e)
|
|
self.activated = True
|
|
|
|
def handle(self, record):
|
|
if self.activated:
|
|
record = logging.Formatter('%(asctime)s - %(levelname)s - %(module)s - %(lineno)d - %(message)s').format(record)
|
|
self.__gateway.send_to_storage(self.__gateway.name, {"deviceName": self.__gateway.name, "telemetry": [{'LOGS': record}]})
|
|
|
|
def deactivate(self):
|
|
self.current_log_level = 'NOTSET'
|
|
self.activated = False
|