-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger_x.py
1785 lines (1638 loc) · 59.8 KB
/
logger_x.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import inspect
import json
import linecache
import logging
import os
import psycopg2
import psycopg2.extras
import socket
import sqlite3
import sys
import textwrap
import traceback
import uvicorn
import uuid
from collections import namedtuple
from datetime import datetime
from dotenv import dotenv_values, find_dotenv, load_dotenv
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from rich.console import Console
from rich.logging import RichHandler
from pydantic import BaseModel, Field
from typing import Any, Dict, NewType, Optional, Tuple, Union
# TODO: Add docstrings to all functions and classes
# TODO: Consider tighening the CORS settings
# Variables and Type Aliases
PostgresConn = psycopg2.extensions.connection
SQLiteConn = NewType("SQLiteConn", sqlite3.Connection)
DatabaseConn = Union[PostgresConn, SQLiteConn]
Detailed_Result = Tuple[
bool,
Optional[Any],
]
logger_x_table = "logger"
DBInfo = namedtuple(
"DBInfo",
[
"LOGGER_MODE",
"LOGGER_DIR",
"DATABASE_PATH",
"DATABASE_USER",
"DATABASE_CRED",
"DATABASE_HOST",
"DATABASE_PORT",
"DATABASE_NAME",
],
)
FullLogInfo = namedtuple(
"FullLogInfo",
["log_id", "uuid", "log_notes", "source", "level", "internal"],
)
LogInfo = namedtuple(
"LogInfo", ["log_notes", "source", "level", "status", "internal"]
)
console = Console()
logging.basicConfig(
level="NOTSET",
format="%(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True)],
)
logger_x = logging.getLogger("rich")
class FullDBEntry(BaseModel):
"""
Pydantic model that includes the standard
fillable fields for a database entry.
"""
log_notes: Optional[str] = None
source: Optional[str] = None
level: Optional[str] = "INFO"
status: Optional[str] = "new"
misc: Optional[str] = None
success: Optional[bool] = False
class UpdateDBLog(BaseModel):
"""
Pydantic model that includes the standard
updatable fields for a database entry.
"""
entry_uuid: str
status: Optional[str] = None
internal: Optional[str] = None
def api_listener(
host: Optional[str] = None,
port: Optional[int] = None,
ssl: Optional[Dict[str, str]] = None,
):
"""
FastAPI listener that listens for incoming
API requests and processes them accordingly.
"""
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
load_dotenv(find_dotenv(usecwd=True))
def verify_secret_key(x_secret_key: str = Header(...)):
if x_secret_key != os.getenv("SECRET_KEY"):
raise HTTPException(status_code=403, detail="Invalid secret key")
@app.post("/add")
async def api_add_entry(
entry: FullDBEntry, secret_key: str = Depends(verify_secret_key)
):
"""
API endpoint that adds a new entry to the database.
"""
try:
determined_level = (
entry.level
if entry.level is not None
else ("ERROR" if not entry.success else "INFO")
)
new_log_entry(
logging_msg=entry.log_notes,
logging_level=determined_level,
source=entry.source,
success=(
bool(entry.success) if entry.success is not None else False
),
misc=entry.misc,
)
return {"status": "success"}
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
return {"status": "failure"}
@app.post("/update/{entry_uuid}")
async def api_update_entry_by_uuid(
entry_uuid: str,
entry: FullDBEntry,
secret_key: str = Depends(verify_secret_key),
):
"""
API endpoint that updates an existing entry in the database.
"""
try:
determined_level = (
entry.level
if entry.level is not None
else ("ERROR" if not entry.success else "INFO")
)
result = update_db_log_by_uuid(
uuid=entry_uuid,
logging_msg=entry.log_notes,
logging_level=determined_level,
source=entry.source,
status=(entry.status if entry.status is not None else "new"),
misc=entry.misc if entry.misc is not None else None,
)
return {"status": "success" if result else "failure"}
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
return {"status": "failure"}
@app.get("/firstlogid")
async def api_first_log_id(secret_key: str = Depends(verify_secret_key)):
"""
API endpoint that fetches the first log ID in the database.
"""
try:
db_connection = connect_database()
first_id = get_first_log_id(db_connection)
close_database(db_connection)
return {"first_log_id": first_id}
except Exception as e:
logger_x.error(
f"Failed to fetch first log ID: {str(e)}", exc_info=True
)
raise HTTPException(
status_code=500, detail="Failed to fetch first log ID"
)
@app.get("/newlogid")
async def api_new_log_id(secret_key: str = Depends(verify_secret_key)):
"""
API endpoint that fetches the next available log ID.
"""
try:
db_connection = connect_database()
new_id = get_new_log_id(db_connection)
close_database(db_connection)
return {"new_log_id": new_id}
except Exception as e:
logger_x.error(
f"Failed to fetch new log ID: {str(e)}", exc_info=True
)
raise HTTPException(
status_code=500, detail="Failed to fetch new log ID"
)
@app.get("/nextlogid/{current_id}")
async def api_next_log_id(
current_id: int, secret_key: str = Depends(verify_secret_key)
):
"""
API endpoint that fetches the next log ID after the current one.
"""
try:
db_connection = connect_database()
try:
next_id = get_next_log_id(current_id, db_connection)
return {"next_log_id": next_id}
except ValueError as ve:
return {"next_log_id": None, "message": str(ve)}
finally:
close_database(db_connection)
except Exception as e:
logger_x.error(
f"Failed to fetch next log ID: {str(e)}", exc_info=True
)
raise HTTPException(
status_code=500, detail="Failed to fetch next log ID"
)
@app.get("/previouslogid/{current_id}")
async def api_previous_log_id(
current_id: int, secret_key: str = Depends(verify_secret_key)
):
"""
API endpoint that fetches the previous log ID before the current one.
"""
try:
db_connection = connect_database()
try:
previous_id = get_previous_log_id(current_id, db_connection)
return {"previous_log_id": previous_id}
except ValueError as ve:
return {"previous_log_id": None, "message": str(ve)}
finally:
close_database(db_connection)
except Exception as e:
logger_x.error(
f"Failed to fetch previous log ID: {str(e)}", exc_info=True
)
raise HTTPException(
status_code=500, detail="Failed to fetch previous log ID"
)
@app.get("/uuid/{log_id}")
async def api_get_uuid(
log_id: int, secret_key: str = Depends(verify_secret_key)
):
"""
API endpoint that fetches the UUID for a given log ID.
"""
try:
db_connection = connect_database()
uuid = get_uuid_by_log_id(db_connection, log_id)
close_database(db_connection)
if uuid:
return {"uuid": uuid}
else:
raise HTTPException(status_code=404, detail="Log ID not found")
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
return {"status": "failure"}
@app.get("/getlog/{uuid}")
async def api_get_log(
uuid: str, secret_key: str = Depends(verify_secret_key)
):
"""
API endpoint that fetches a log entry by UUID.
"""
try:
db_connection = connect_database()
log = get_log_by_uuid(db_connection, uuid)
close_database(db_connection)
if log:
return log
else:
raise HTTPException(status_code=404, detail="UUID not found")
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
return {"status": "failure"}
@app.get("/checkid/{log_id}")
async def api_check_log_id(
log_id: int, secret_key: str = Depends(verify_secret_key)
):
"""
API endpoint that checks if a log ID exists in the database.
"""
try:
db_connection = connect_database()
check = check_log_id_exists(db_connection, log_id)
close_database(db_connection)
return {"exists": check}
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
return {"status": "failure"}
@app.delete("/admindeletelog/{log_id}/{uuid}/")
async def api_delete_log(
log_id: int,
uuid: str,
secret_key: str = Depends(verify_secret_key),
):
"""
API endpoint that allows an admin to delete a log entry.
"""
try:
db_connection = connect_database()
cursor = db_connection.cursor()
if not check_log_id_exists(db_connection, log_id):
cursor.close()
close_database(db_connection)
raise HTTPException(
status_code=404, detail="Log ID and UUID not found"
)
result = delete_log_admin(db_connection, log_id, uuid)
cursor.close()
close_database(db_connection)
return result
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
close_database(db_connection)
return {"status": "failure"}
@app.delete("/deletelog/{log_id}/{uuid}/")
async def api_update_log_to_deleted(
log_id: int,
uuid: str,
secret_key: str = Depends(verify_secret_key),
):
"""
API endpoint that updates a log entry to a deleted status.
"""
try:
db_connection = connect_database()
cursor = db_connection.cursor()
if not check_log_id_exists(db_connection, log_id):
cursor.close()
close_database(db_connection)
raise HTTPException(
status_code=404, detail="Log ID and UUID not found"
)
result = set_log_to_deleted(db_connection, log_id, uuid)
cursor.close()
close_database(db_connection)
return result
except Exception as e:
exception = HTTPException(status_code=500, detail=str(e))
new_log_entry(exception=exception, logging_level="CRITICAL")
close_database(db_connection)
return {"status": "failure"}
api_host = os.getenv("API_HOST", "0.0.0.0") if host is None else host
api_port = os.getenv("API_PORT", 8000) if port is None else port
ssl_key_file = (
os.getenv("SSL_KEY_FILE", None) if ssl is None else ssl["key"]
)
ssl_cert_file = (
os.getenv("SSL_CERT_FILE", None) if ssl is None else ssl["cert"]
)
ssl_enabled = (
True
if (ssl_key_file is not None and ssl_cert_file is not None)
else False
)
uvicorn_args = {
"host": api_host,
"port": api_port,
}
if ssl_enabled:
uvicorn_args["ssl_keyfile"] = ssl_key_file
uvicorn_args["ssl_certfile"] = ssl_cert_file
uvicorn.run(app, **uvicorn_args)
def build_debug_message(
date_time: Optional[str] = None,
level: Optional[str] = None,
log_notes: Optional[str] = None,
source: Optional[str] = None,
status: Optional[str] = None,
internal: Optional[str] = None,
) -> str:
"""
Build a debug message for logging purposes.
"""
rich_datetime = datetime.utcnow() if date_time is None else date_time
rich_level = "ERROR" if level is None else level
rich_log_notes = (
"Something went wrong (generic error message)."
if log_notes is None
else log_notes
)
rich_source = socket.getfqdn().lower() if source is None else source
rich_status = "new" if status is None else status
try:
debug_message = (
f"date_time: {rich_datetime}\n"
f"level: {rich_level}\n"
f"log_notes: {rich_log_notes}\n"
f"source: {rich_source}\n"
f"status: {rich_status}\n"
)
if internal:
debug_message += f"internal: {internal}\n"
debug_message += "\n"
return debug_message
except Exception as e:
error_message = (
f"Error in build_debug_message(): {e}\n\n"
"Something went really really wrong here..."
)
return error_message
def build_logger_table() -> None:
"""
Build the logger table in the database.
"""
try:
db_connection = connect_database()
if not table_exists(db_connection, logger_x_table):
create_new_database(db_connection)
else:
logger_x.info(f"The {logger_x_table} table already exists")
close_database(db_connection)
except Exception as e:
logger_x.error(
f"Failed to create {logger_x_table} table: {str(e)}",
exc_info=True,
)
raise RuntimeError(f"Failed to create {logger_x_table} table")
def check_file_permissions(path: str, apply_to_path: str) -> None:
"""
Check the permissions of a file or directory and apply them to another.
"""
root_permissions = os.stat("./").st_mode
os.chmod(apply_to_path, root_permissions)
if os.path.isdir(apply_to_path):
for dirpath, dirnames, filenames in os.walk(apply_to_path):
for dn in dirnames:
os.chmod(os.path.join(dirpath, dn), root_permissions)
for fn in filenames:
os.chmod(os.path.join(dirpath, fn), root_permissions)
def check_function(
path: str, create_dir: bool = False, is_directory: bool = True
) -> bool:
"""
Check if a file or directory exists at the given path.
"""
if os.path.exists(path):
if (is_directory and os.path.isdir(path)) or (
not is_directory and os.path.isfile(path)
):
return True
else:
expected_type = "directory" if is_directory else "file"
raise ValueError(f"{path} is not a {expected_type}")
if is_directory:
if create_dir:
os.makedirs(path, exist_ok=True)
check_file_permissions("./", path)
return True
else:
raise FileNotFoundError(f"Directory {path} does not exist")
else:
raise FileNotFoundError(f"File {path} does not exist")
def check_log_id_exists(db_connection: DatabaseConn, log_id: int) -> bool:
"""
Check if a log ID exists in the database.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"SELECT id FROM {logger_x_table} WHERE id = %s", (log_id,)
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"SELECT id FROM {logger_x_table} WHERE id = ?", (log_id,)
)
else:
raise Exception("Unsupported database connection type")
if not cursor.fetchone():
return False
return True
finally:
cursor.close()
def close_database(connection) -> Optional[bool]:
"""
Close the database connection.
"""
try:
connection.close()
return True
except Exception as e:
raise Exception(f"[close_database({type(connection)}) failed]:{e}")
def connect_database(
data_path: Optional[str] = None,
) -> Union[PostgresConn, SQLiteConn]:
"""
Connect to the database using the provided credentials.
"""
load_dotenv(find_dotenv(usecwd=True))
def postgresql_connect() -> PostgresConn:
try:
connection = psycopg2.connect(
dbname=os.getenv("DATABASE_NAME", logger_x_table),
user=os.getenv("DATABASE_USER", "root"),
password=os.getenv("DATABASE_CRED", "password"),
host=os.getenv("DATABASE_HOST", "localhost"),
port=os.getenv("DATABASE_PORT", 5432),
)
return connection
except Exception as e:
raise Exception(
f"[Failed postgresql_connect() in connect_database()]:{e}"
)
def sqlite_connect(db_path: Optional[str] = None) -> SQLiteConn:
try:
if db_path != ":memory:":
if db_path is None:
db_path = os.getenv("DATABASE_PATH", ":memory:")
connection = sqlite3.connect(str(db_path))
else:
connection = sqlite3.connect(":memory:")
return SQLiteConn(connection)
except Exception as e:
raise Exception(
f"[Failed sqlite_connect({db_path}) in connect_database()]:{e}"
)
try:
logger_mode = os.getenv("LOGGER_MODE", "file")
if logger_mode == "postgresql":
return postgresql_connect()
elif logger_mode == "sqlite":
return sqlite_connect(data_path)
elif logger_mode == "file":
raise Exception(
"This should not be happening."
"db_connect() called with LOGGER_MODE set to file."
)
else:
raise Exception(f"{logger_mode} is either invalid or unsupported.")
except Exception as e:
err_1 = "[connect_database("
err_2 = f"{os.getenv('DATABASE_MODE', '')}) failed]:{e}"
raise Exception(err_1 + err_2)
def create_db_log(log_info: LogInfo, db_connection: DatabaseConn) -> bool:
"""
Insert a new log entry into the database logger.
"""
cursor = None
try:
cursor = db_connection.cursor()
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"""
INSERT INTO {logger_x_table}
(level, source, log_notes, status, last_updated, internal)
VALUES (%s, %s, %s, %s, %s, %s)
""",
(
log_info.level,
log_info.source,
log_info.log_notes,
log_info.status,
get_timestamp_for_log(),
log_info.internal,
),
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"""
INSERT INTO {logger_x_table}
(level, source, log_notes, status, last_updated, uuid, internal)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
log_info.level,
log_info.source,
log_info.log_notes,
log_info.status,
get_timestamp_for_log(),
str(uuid.uuid4()),
log_info.internal,
),
)
else:
raise Exception(
f"Invalid database mode: {os.environ['LOGGER_MODE']}"
)
db_connection.commit()
cursor.close() if cursor else None
return True
except Exception as e:
cursor.close() if cursor else None
close_database(db_connection) if db_connection else None
error_message = build_debug_message(
level=log_info.level,
log_notes=log_info.log_notes,
source=log_info.source,
status=log_info.status,
internal=log_info.internal,
)
logger_x.critical(
f"[create_database_log({type(db_connection)}) failed]"
f"[Exception]:{e}\n\n"
f"[Detailed Info]:\n{error_message}"
)
return False
def create_new_database(db_connection: DatabaseConn) -> bool:
"""
Create a new logger database table.
"""
cursor = None
try:
cursor = db_connection.cursor()
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS {logger_x_table} (
id SERIAL PRIMARY KEY,
datetime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
level VARCHAR(32) NOT NULL,
source VARCHAR(1024) NOT NULL,
log_notes TEXT,
status VARCHAR(255) NOT NULL DEFAULT 'new',
last_updated TIMESTAMP,
uuid VARCHAR(255) NOT NULL UNIQUE DEFAULT uuid_generate_v4(),
internal JSONB
)
"""
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS {logger_x_table} (
id INTEGER PRIMARY KEY,
datetime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
level VARCHAR(32) NOT NULL,
source VARCHAR(1024) NOT NULL,
log_notes TEXT,
status VARCHAR(255) NOT NULL DEFAULT 'new',
last_updated TIMESTAMP,
uuid UUID NOT NULL UNIQUE,
internal TEXT
)
"""
)
else:
raise Exception(
f"[create_new_database({type(db_connection)}) failed]:"
f"Invalid database mode: {os.environ['LOGGER_MODE']}"
)
db_connection.commit()
cursor.close() if cursor else None
return True
except Exception as e:
if cursor:
cursor.close()
if db_connection:
close_database(db_connection)
logging_info = build_debug_message(
level="CRITICAL",
log_notes=str(e),
)
new_log_entry(e, logging_info, "CRITICAL")
return False
def delete_log_admin(db_connection: DatabaseConn, log_id: int, uuid: str):
"""
Delete a log entry from the database.
"""
try:
cursor = db_connection.cursor()
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"DELETE FROM {logger_x_table} WHERE id = %s AND uuid = %s",
(log_id, uuid),
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"DELETE FROM {logger_x_table} WHERE id = ? AND uuid = ?",
(log_id, uuid),
)
else:
raise Exception("Unsupported database connection type")
db_connection.commit()
cursor.close()
return {"status": "success"}
except Exception as e:
cursor.close()
close_database(db_connection)
raise Exception(f"[delete_log_admin() failed]: {e}")
def dir_check(dir_path: str, create_dir: bool = True) -> bool:
"""
Check if a directory exists at the given path.
"""
return check_function(dir_path, create_dir, is_directory=True)
def fetch_log_path() -> str:
"""
Fetch the path to the log file.
"""
try:
log_dir = os.path.join(
os.getenv("LOGGER_DIR", os.path.join(os.getcwd(), ".logs"))
)
today = datetime.utcnow()
time_stamp = today.strftime("%Y%m%d")
if not dir_check(log_dir):
raise FileNotFoundError(
f"[{log_dir}] does not exist. Please create it and try again."
)
return os.path.join(log_dir, f"{time_stamp}.log")
except Exception as e:
raise RuntimeError(f"[fetch_log_path() failed]: {e}")
def file_exists(file_path: str) -> bool:
"""
Check if a file exists at the given path.
"""
return check_function(file_path, is_directory=False)
def format_datetime(
input_time: datetime, milliseconds: bool = False
) -> Optional[str]:
"""
Format a datetime object to a string.
"""
try:
if isinstance(input_time, (int, float)):
input_time = datetime.fromtimestamp(input_time / 1000)
else:
input_time = datetime.strptime(
str(input_time), "%Y-%m-%d %H:%M:%S.%f"
)
if milliseconds:
return input_time.strftime("%Y-%m-%d %H:%M:%S.%f")
else:
return input_time.strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, TypeError) as e:
err_1 = f"[format_datetime({input_time})"
err_2 = f", {milliseconds}" if milliseconds else ""
err_3 = f"] failed: {e}"
raise Exception(err_1 + err_2 + err_3)
def get_first_log_id(db_connection: DatabaseConn) -> int:
"""
Fetch the first log ID in the database.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(f"SELECT MIN(id) FROM {logger_x_table}")
elif type(db_connection) == SQLiteConn:
cursor.execute(f"SELECT MIN(id) FROM {logger_x_table}")
else:
raise Exception("Unsupported database connection type")
result = cursor.fetchone()
min_id = result[0] if result and result[0] is not None else 1
return min_id
finally:
cursor.close()
def get_log_by_uuid(
db_connection: DatabaseConn, uuid: str
) -> Optional[Dict[str, Any]]:
"""
Fetch a log entry by UUID.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"SELECT id, uuid, log_notes, source, level, internal, datetime, last_updated FROM {logger_x_table} WHERE uuid = %s",
(uuid,),
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"SELECT id, uuid, log_notes, source, level, internal, datetime, last_updated FROM {logger_x_table} WHERE uuid = ?",
(uuid,),
)
else:
raise Exception("Unsupported database connection type")
log = cursor.fetchone()
if log:
return {
"log_id": log[0],
"uuid": log[1],
"log_notes": log[2],
"source": log[3],
"level": log[4],
"internal": json_to_string(log[5])[1] if log[5] else None,
"datetime": (log[6]),
"last_updated": ((log[7]) if log[7] else None),
}
else:
raise HTTPException(status_code=404, detail="UUID not found")
finally:
cursor.close()
def get_new_log_id(db_connection: DatabaseConn) -> int:
"""
Fetch the next available log ID.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(f"SELECT MAX(id) FROM {logger_x_table}")
elif type(db_connection) == SQLiteConn:
cursor.execute(f"SELECT MAX(id) FROM {logger_x_table}")
else:
raise Exception("Unsupported database connection type")
result = cursor.fetchone()
max_id = result[0] if result and result[0] is not None else 0
return max_id + 1
finally:
cursor.close()
def get_next_log_id(current_id: int, db_connection: DatabaseConn) -> int:
"""
Fetch the next log ID after the current one, skipping logs with status 'deleted'.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"SELECT MIN(id) FROM {logger_x_table} WHERE id > %s AND status != 'deleted'",
(current_id,),
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"SELECT MIN(id) FROM {logger_x_table} WHERE id > ? AND status != 'deleted'",
(current_id,),
)
else:
raise Exception("Unsupported database connection type")
result = cursor.fetchone()
next_id = result[0] if result and result[0] is not None else None
if next_id is None:
raise ValueError("No next log exists")
return next_id
finally:
cursor.close()
def get_previous_log_id(current_id: int, db_connection: DatabaseConn) -> int:
"""
Fetch the previous log ID before the current one, skipping logs with status 'deleted'.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"SELECT MAX(id) FROM {logger_x_table} WHERE id < %s AND status != 'deleted'",
(current_id,),
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"SELECT MAX(id) FROM {logger_x_table} WHERE id < ? AND status != 'deleted'",
(current_id,),
)
else:
raise Exception("Unsupported database connection type")
result = cursor.fetchone()
previous_id = result[0] if result and result[0] is not None else None
if previous_id is None:
raise ValueError("No previous log exists")
return previous_id
finally:
cursor.close()
def get_uuid_by_log_id(db_connection: DatabaseConn, log_id: int) -> str:
"""
Fetch the UUID for a given log ID.
"""
cursor = db_connection.cursor()
try:
if isinstance(db_connection, PostgresConn):
cursor.execute(
f"SELECT uuid FROM {logger_x_table} WHERE id = %s",
(log_id,),
)
elif type(db_connection) == SQLiteConn:
cursor.execute(
f"SELECT uuid FROM {logger_x_table} WHERE id = ?",
(log_id,),
)
else:
raise Exception("Unsupported database connection type")
uuid = cursor.fetchone()
if uuid:
return uuid[0] if uuid else ""
else:
raise HTTPException(status_code=404, detail="Log ID not found")
finally:
cursor.close()
def get_timestamp_for_log(milliseconds: bool = True) -> str:
"""
Get the current timestamp for logging purposes.
"""
return str(format_datetime(datetime.utcnow(), milliseconds))
def json_to_string(json_package: Dict[str, str]) -> Detailed_Result:
"""
Convert a JSON package to a string.
"""
try:
json_converted = json.dumps(
json_package, ensure_ascii=False, separators=(",", ":")
)
if json_converted is None:
return False, f"{json_converted} is None"
if not isinstance(json_converted, str):
try:
json_converted = str(json_converted)
except ValueError:
return False, f"{json_converted} is a {type(json_converted)}"
if len(json_converted) == 0:
return False, f"{json_converted} is empty"
return True, json_converted
except (TypeError, ValueError) as e: