]> git.mxchange.org Git - fba.git/blob - fba/models/error_log.py
3e6e35b8e123e1eab56b5d4beec121a20d972c77
[fba.git] / fba / models / error_log.py
1 # Copyright (C) 2023 Free Software Foundation
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License as published
5 # by the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU Affero General Public License for more details.
12 #
13 # You should have received a copy of the GNU Affero General Public License
14 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16 import logging
17 import json
18 import time
19
20 from fba import database
21
22 from fba.helpers import config
23 from fba.helpers import domain as domain_helper
24
25 logging.basicConfig(level=logging.INFO)
26 logger = logging.getLogger(__name__)
27
28 def add(domain: str, error: dict):
29     logger.debug("domain='%s',error[]='%s' - CALLED!", domain, type(error))
30     domain_helper.raise_on(domain)
31
32     if config.get("write_error_log").lower() != "true":
33         logger.debug("Writing to error_log is disabled in configuruation file - EXIT!")
34         return
35
36     logger.debug("error[]='%s' - BEFORE!", type(error))
37     if isinstance(error, (BaseException, json.decoder.JSONDecodeError)):
38         error = f"error[{type(error)}]='{str(error)}'"
39     logger.debug("error[]='%s' - AFTER!", type(error))
40
41     if isinstance(error, str):
42         database.cursor.execute("INSERT INTO error_log (domain, error_code, error_message, created) VALUES (?, 999, ?, ?)",[
43             domain,
44             error,
45             time.time()
46         ])
47     else:
48         database.cursor.execute("INSERT INTO error_log (domain, error_code, error_message, created) VALUES (?, ?, ?, ?)",[
49             domain,
50             error["status_code"],
51             error["error_message"],
52             time.time()
53         ])
54
55     # Cleanup old entries
56     logger.debug("Purging old records (distance: %d)", config.get('error_log_cleanup'))
57     database.cursor.execute("DELETE FROM error_log WHERE created < ?", [time.time() - config.get("error_log_cleanup")])
58
59     logger.debug("EXIT!")