csc-cia-stne 0.0.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
1
+ import os
2
+
3
+ class Karavela():
4
+
5
+ def __init__(self)->None:
6
+ """Inicia a instância da classe Karavela
7
+
8
+ """
9
+ self.healthy_check_file = None
10
+
11
+ def create_health_check_file(self,health_check_filename:str = None)->bool:
12
+ """Cria o arquivo de health check
13
+
14
+ Args:
15
+ health_check_file (str): nome do arquivo de health check a ser criado
16
+ Returns:
17
+ bool: True
18
+ """
19
+
20
+ if health_check_filename is None or health_check_filename == "":
21
+
22
+ raise ValueError("O método 'create_health_check_file' precisa do parâmetro health_check_filename especificado")
23
+
24
+ self.health_check_filename = health_check_filename
25
+
26
+ try:
27
+
28
+ if not os.path.exists(self.health_check_filename):
29
+
30
+ directory = os.path.dirname(self.health_check_filename)
31
+
32
+ if not os.path.exists(directory) and str(directory).strip() != "":
33
+
34
+ os.makedirs(directory)
35
+
36
+ with open(f'{self.health_check_filename}', 'w') as f:
37
+
38
+ f.write('OK!')
39
+ return True
40
+
41
+ except Exception as e:
42
+
43
+ raise e
44
+
45
+ def destroy_health_check_file(self)->bool:
46
+ """Deleta o arquivo de health check
47
+
48
+ Returns:
49
+ bool: True
50
+ """
51
+
52
+ if self.health_check_filename is None:
53
+
54
+ raise ValueError("O método 'create_health_check_file' precisa ser executado antes")
55
+
56
+ try:
57
+
58
+ if os.path.exists(self.health_check_filename):
59
+
60
+ os.remove(self.health_check_filename)
61
+ return True
62
+
63
+ else:
64
+
65
+ return True
66
+
67
+ except Exception as e:
68
+
69
+ raise e
70
+
71
+ def get_secret(self,name:str)->str:
72
+ """Extrai a secret do ambiente
73
+
74
+ Args:
75
+ name (str): nome da variavel ou arquivo da secret
76
+
77
+ Returns:
78
+ str: string da secret armazenada na variável de ambiente ou no arquivo de secret
79
+ """
80
+
81
+ # Tentando extrair da variavel de ambiente
82
+ secret = os.getenv(name)
83
+
84
+ # secret não encontrada em variavel de ambiente, tentando extrair do arquivo em /secret
85
+ if secret is None:
86
+
87
+ # verifica na pasta ./secrets
88
+ if os.path.exists(f"./secrets/{name}"):
89
+
90
+ with open(f"./secrets/{name}",'r') as secret_file:
91
+
92
+ secret = secret_file.read()
93
+
94
+ # verifica na pasta ./.secrets
95
+ elif os.path.exists(f"./.secrets/{name}"):
96
+
97
+ with open(f"./.secrets/{name}",'r') as secret_file:
98
+
99
+ secret = secret_file.read()
100
+
101
+ # verifica na pasta ./private
102
+ elif os.path.exists(f"./private/{name}"):
103
+
104
+ with open(f"./private/{name}",'r') as secret_file:
105
+
106
+ secret = secret_file.read()
107
+
108
+ # verifica na pasta ./.private
109
+ elif os.path.exists(f"./.private/{name}"):
110
+
111
+ with open(f"./.private/{name}",'r') as secret_file:
112
+
113
+ secret = secret_file.read()
114
+
115
+ # verifica na pasta /secrets
116
+ elif os.path.exists(f"/secrets/{name}"):
117
+
118
+ with open(f"/secrets/{name}",'r') as secret_file:
119
+
120
+ secret = secret_file.read()
121
+
122
+ return secret
123
+
csc_cia_stne/logger.py ADDED
@@ -0,0 +1,155 @@
1
+ import os
2
+ import logging
3
+ import colorlog
4
+ from pythonjsonlogger import jsonlogger
5
+
6
+
7
+ # Strategy para formatação dos logs
8
+ class LogFormatterStrategy:
9
+ """
10
+ Interface para estratégia de formatação de logs.
11
+ Define o método `format`, que deve ser implementado pelas subclasses.
12
+ """
13
+
14
+ def format(self, log_handler, date_format):
15
+ """
16
+ Aplica a formatação do log ao handler fornecido.
17
+
18
+ Parâmetros:
19
+ log_handler (logging.Handler): O handler que receberá a formatação.
20
+ date_format (str): O formato da data para os logs.
21
+
22
+ Retorna:
23
+ None
24
+ """
25
+ raise NotImplementedError("O método format() deve ser implementado")
26
+
27
+
28
+ class ColorLogFormatter(LogFormatterStrategy):
29
+ """
30
+ Implementação da estratégia de formatação de logs coloridos para uso local.
31
+ """
32
+
33
+ def format(self, log_handler, date_format):
34
+ """
35
+ Aplica a formatação colorida ao handler de log.
36
+
37
+ Parâmetros:
38
+ log_handler (logging.Handler): O handler que receberá a formatação.
39
+ date_format (str): O formato da data para os logs.
40
+
41
+ Retorna:
42
+ None
43
+ """
44
+ formatter = colorlog.ColoredFormatter(
45
+ "%(asctime)s - %(log_color)s%(levelname)s%(reset)s - %(message)s",
46
+ datefmt=date_format,
47
+ log_colors={
48
+ "DEBUG": "reset",
49
+ "INFO": "green",
50
+ "WARNING": "yellow",
51
+ "ERROR": "red",
52
+ "CRITICAL": "bold_red",
53
+ },
54
+ )
55
+ log_handler.setFormatter(formatter)
56
+
57
+
58
+ class JsonLogFormatter(LogFormatterStrategy):
59
+ """
60
+ Implementação da estratégia de formatação de logs em JSON, ideal para ambientes como Docker.
61
+ """
62
+
63
+ def format(self, log_handler, date_format):
64
+ """
65
+ Aplica a formatação JSON ao handler de log.
66
+
67
+ Parâmetros:
68
+ log_handler (logging.Handler): O handler que receberá a formatação.
69
+ date_format (str): O formato da data para os logs.
70
+
71
+ Retorna:
72
+ None
73
+ """
74
+ formatter = jsonlogger.JsonFormatter(
75
+ "%(asctime)s - %(levelname)s - %(message)s", datefmt=date_format
76
+ )
77
+ log_handler.setFormatter(formatter)
78
+
79
+
80
+ # Factory para criar o logger
81
+ class LoggerFactory:
82
+ """
83
+ Classe de fábrica responsável por criar e configurar loggers.
84
+ """
85
+
86
+ @staticmethod
87
+ def create_logger(name):
88
+ """
89
+ Cria e retorna um logger configurado com o nome especificado.
90
+
91
+ Parâmetros:
92
+ name (str): O nome do logger.
93
+
94
+ Retorna:
95
+ logging.Logger: O logger configurado.
96
+ """
97
+ try:
98
+ if not os.path.exists("./tmp"):
99
+ os.makedirs("./tmp")
100
+ except OSError as e:
101
+ print(f"Erro ao criar o diretório './tmp': {e}")
102
+ raise
103
+
104
+ logger = logging.getLogger(name)
105
+ logger.setLevel(logging.INFO)
106
+ log_handler = logging.StreamHandler()
107
+ date_format = "%d-%m-%Y %H:%M:%S"
108
+
109
+ # Define a estratégia de formatação dependendo do ambiente
110
+ if LoggerFactory.not_docker():
111
+ formatter_strategy = ColorLogFormatter()
112
+
113
+ # Configura o handler para salvar logs em arquivo
114
+ file_handler = logging.FileHandler("tmp/log.txt")
115
+ file_handler.setFormatter(
116
+ logging.Formatter(
117
+ "%(asctime)s - %(levelname)s - %(message)s",
118
+ datefmt=date_format,
119
+ )
120
+ )
121
+ logger.addHandler(file_handler)
122
+ else:
123
+ formatter_strategy = JsonLogFormatter()
124
+ print("Rodando em container, logs em JSON")
125
+
126
+ # Aplica a estratégia de formatação
127
+ formatter_strategy.format(log_handler, date_format)
128
+ logger.addHandler(log_handler)
129
+
130
+ return logger
131
+
132
+ @staticmethod
133
+ def not_docker():
134
+ """
135
+ Verifica se o código está sendo executado em um container Docker.
136
+
137
+ Retorna:
138
+ bool: False se estiver rodando em um container Docker, True se estiver rodando localmente.
139
+ """
140
+ if os.path.exists("/.dockerenv"):
141
+ return False
142
+
143
+ try:
144
+ with open("/proc/1/cgroup", "rt") as file:
145
+ for line in file:
146
+ if "docker" in line or "kubepods" in line:
147
+ return False
148
+ except Exception:
149
+ print("Logger sendo executado localmente.")
150
+
151
+ return True
152
+
153
+
154
+ # Uso do logger
155
+ logger = LoggerFactory.create_logger(__name__)