csc-cia-stne 0.0.15__py3-none-any.whl → 0.0.17__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.
- csc_cia_stne/__init__.py +3 -2
- csc_cia_stne/functions.py +88 -0
- csc_cia_stne/logger_rich.py +5 -1
- csc_cia_stne/settings.py +4 -2
- {csc_cia_stne-0.0.15.dist-info → csc_cia_stne-0.0.17.dist-info}/METADATA +1 -1
- {csc_cia_stne-0.0.15.dist-info → csc_cia_stne-0.0.17.dist-info}/RECORD +9 -9
- csc_cia_stne/cia_logging.py +0 -149
- {csc_cia_stne-0.0.15.dist-info → csc_cia_stne-0.0.17.dist-info}/LICENCE +0 -0
- {csc_cia_stne-0.0.15.dist-info → csc_cia_stne-0.0.17.dist-info}/WHEEL +0 -0
- {csc_cia_stne-0.0.15.dist-info → csc_cia_stne-0.0.17.dist-info}/top_level.txt +0 -0
csc_cia_stne/__init__.py
CHANGED
@@ -1,12 +1,13 @@
|
|
1
1
|
import os
|
2
|
-
|
2
|
+
from .settings import settings
|
3
|
+
|
4
|
+
if os.getenv('ambiente_de_execucao') is not None and os.getenv('ambiente_de_execucao') == "karavela":
|
3
5
|
from .logger_json import logger
|
4
6
|
else:
|
5
7
|
from .logger_rich import logger
|
6
8
|
from .karavela import Karavela
|
7
9
|
from .utilitarios import Util
|
8
10
|
from .servicenow import ServiceNow
|
9
|
-
from .cia_logging import logger
|
10
11
|
from .stne_admin import StoneAdmin
|
11
12
|
from .bc_sta import BC_STA
|
12
13
|
from .bc_correios import BC_Correios
|
@@ -0,0 +1,88 @@
|
|
1
|
+
import os
|
2
|
+
import base64
|
3
|
+
import mimetypes
|
4
|
+
from datetime import datetime
|
5
|
+
from rich import print
|
6
|
+
from rich.panel import Panel
|
7
|
+
from rich.style import Style
|
8
|
+
import json
|
9
|
+
import shutil
|
10
|
+
import logging
|
11
|
+
|
12
|
+
# Retorna data de modificação
|
13
|
+
def last_modified()->datetime:
|
14
|
+
"""
|
15
|
+
Retorna a data da última atualização do script
|
16
|
+
|
17
|
+
"""
|
18
|
+
current_file = os.path.abspath(__file__)
|
19
|
+
current_folder = os.path.dirname(current_file)
|
20
|
+
base_dir = os.path.dirname(os.path.dirname(current_file))
|
21
|
+
|
22
|
+
newest_date = None
|
23
|
+
|
24
|
+
for root, _, files in os.walk(base_dir):
|
25
|
+
|
26
|
+
for file in files:
|
27
|
+
|
28
|
+
if file.endswith('.py'):
|
29
|
+
|
30
|
+
file_path = os.path.join(root, file)
|
31
|
+
file_modification_date = os.path.getmtime(file_path)
|
32
|
+
|
33
|
+
if newest_date is None or file_modification_date > newest_date:
|
34
|
+
|
35
|
+
newest_date = file_modification_date
|
36
|
+
|
37
|
+
# Converter o timestamp para um objeto datetime
|
38
|
+
last_modified_date = datetime.fromtimestamp(newest_date)
|
39
|
+
last_modified_date = last_modified_date.strftime("%Y%m%d")
|
40
|
+
|
41
|
+
return last_modified_date
|
42
|
+
|
43
|
+
def titulo():
|
44
|
+
|
45
|
+
if os.getenv('ambiente_de_execucao') is None or os.getenv('ambiente_de_execucao') != "karavela":
|
46
|
+
|
47
|
+
estilo_box = Style(bold=True)
|
48
|
+
print(
|
49
|
+
Panel(
|
50
|
+
f"""
|
51
|
+
[bold chartreuse3]CIA [bold white]| [bold chartreuse3]Centro de Inteligência e Automação [bold white]([bold chartreuse3]cia@stone.com.br[bold white])[bold green]\n
|
52
|
+
Projeto[bold white]: [bold green]{os.getenv('project_name')}\n
|
53
|
+
Versão[bold white]: [bold green]{os.getenv('project_version')}\n
|
54
|
+
Dev[bold white]: [bold green]{os.getenv('project_dev_name')} [bold white]([bold green]{os.getenv('project_dev_mail')}[bold white])[bold green]\n
|
55
|
+
Última atualização[bold white]: [bold green]{last_modified()}
|
56
|
+
""",
|
57
|
+
title="Stone",
|
58
|
+
subtitle="CSC-CIA",
|
59
|
+
style=estilo_box,
|
60
|
+
border_style="bold chartreuse3"
|
61
|
+
)
|
62
|
+
)
|
63
|
+
|
64
|
+
else:
|
65
|
+
|
66
|
+
logging.info("CSC | CIA - Centro de Inteligência e Automação")
|
67
|
+
logging.info(f"Projeto: {os.getenv('project_name')}")
|
68
|
+
logging.info(f"\tVersão: {os.getenv('project_version')} (Última modificação: {last_modified()})")
|
69
|
+
logging.info("\tTime: CIA <cia@stone.com.br>")
|
70
|
+
logging.info(f"\tDesenvolvedor: {os.getenv('project_dev_name')} <{os.getenv('project_dev_mail')}>")
|
71
|
+
logging.info("-")
|
72
|
+
|
73
|
+
def recriar_pasta(caminho_pasta):
|
74
|
+
|
75
|
+
try:
|
76
|
+
|
77
|
+
# Se a pasta já existir, remove-a
|
78
|
+
if os.path.exists(caminho_pasta) and os.path.isdir(caminho_pasta):
|
79
|
+
shutil.rmtree(caminho_pasta) # Deleta a pasta e todo o conteúdo
|
80
|
+
|
81
|
+
# Cria a pasta novamente
|
82
|
+
os.makedirs(caminho_pasta)
|
83
|
+
return True, None
|
84
|
+
|
85
|
+
except Exception as e:
|
86
|
+
|
87
|
+
return False, e
|
88
|
+
|
csc_cia_stne/logger_rich.py
CHANGED
@@ -7,7 +7,11 @@ import traceback
|
|
7
7
|
import os
|
8
8
|
|
9
9
|
# Definindo o nível de log baseado nas configurações
|
10
|
-
if os.getenv('log_level')
|
10
|
+
if os.getenv('log_level') is None:
|
11
|
+
|
12
|
+
log_config_level = logging.DEBUG
|
13
|
+
|
14
|
+
elif os.getenv('log_level') == "DEBUG":
|
11
15
|
|
12
16
|
log_config_level = logging.DEBUG
|
13
17
|
|
csc_cia_stne/settings.py
CHANGED
@@ -2,7 +2,7 @@ from pydantic_settings import BaseSettings
|
|
2
2
|
from pydantic import ValidationError
|
3
3
|
from rich.traceback import install
|
4
4
|
from dotenv import load_dotenv
|
5
|
-
|
5
|
+
from .functions import titulo
|
6
6
|
# Instala formatações de exception da biblioteca Rich
|
7
7
|
install()
|
8
8
|
|
@@ -43,5 +43,7 @@ def load_settings():
|
|
43
43
|
f"As seguintes variáveis obrigatórias estão ausentes no arquivo .env ou nas variáveis de ambiente da máquina: {missing_vars_str}\n"
|
44
44
|
"Outras variáveis, não obrigatórias: 'ambiente_de_execução' ('local' ou 'karavela') e 'log_level' ('DEBUG', 'INFO', etc)"
|
45
45
|
)
|
46
|
-
|
46
|
+
|
47
|
+
titulo()
|
48
|
+
|
47
49
|
settings = load_settings()
|
@@ -1,17 +1,17 @@
|
|
1
|
-
csc_cia_stne/__init__.py,sha256=
|
1
|
+
csc_cia_stne/__init__.py,sha256=dmkzdj7Jvw0jI_ysuSooYrxKrdKL6dYSo7SONMwjU-4,451
|
2
2
|
csc_cia_stne/bc_correios.py,sha256=ANsvLyL7wdkM0MvjjBHB2Ih4eyTcyWgt5IqiK0Rv89E,23014
|
3
3
|
csc_cia_stne/bc_sta.py,sha256=I9N29wjTbd4ZmoM2yIW-xp3X-dMENZdSb0JhapfCegY,10988
|
4
|
-
csc_cia_stne/
|
4
|
+
csc_cia_stne/functions.py,sha256=4hORd_tqzXm5VL-AuIOv-ZkWsUqdC6COe9G_ttVFNUg,3004
|
5
5
|
csc_cia_stne/gcp_bigquery.py,sha256=f8UEQgr6XyFacYX0bRq4UDmWoH-0XqZF8fA2LsLTtAU,5654
|
6
6
|
csc_cia_stne/karavela.py,sha256=Q7MbQXXz_jtrLHM7QeenbSzcro07EpoFk4lKglivJ_I,3564
|
7
7
|
csc_cia_stne/logger_json.py,sha256=2G0rm0lyCtHn4o2v7fzn4wMylb0A_nbxiQatnrSZxHs,1212
|
8
|
-
csc_cia_stne/logger_rich.py,sha256=
|
8
|
+
csc_cia_stne/logger_rich.py,sha256=LU6VGnus-1tPmdacuIphTDxxfQU0Uvl68BKVKLDuHzg,3290
|
9
9
|
csc_cia_stne/servicenow.py,sha256=vSsNSANFyCZtDu2O7YmdoCbr-_bO1sgMWnOI29mFBOA,23311
|
10
|
-
csc_cia_stne/settings.py,sha256=
|
10
|
+
csc_cia_stne/settings.py,sha256=Z0JxshKlC7Oz1-iR8H5Y-tgstL_iQpYneaeMDQ3PW1o,1600
|
11
11
|
csc_cia_stne/stne_admin.py,sha256=G5ozXt18VjKL2BHtROQk4GnfVY1xM14RXSQ-rra_D54,15487
|
12
12
|
csc_cia_stne/utilitarios.py,sha256=LU8YrELiRIW4UxqULjiUPYmgbEx79NGenK5QKRdSh_E,2050
|
13
|
-
csc_cia_stne-0.0.
|
14
|
-
csc_cia_stne-0.0.
|
15
|
-
csc_cia_stne-0.0.
|
16
|
-
csc_cia_stne-0.0.
|
17
|
-
csc_cia_stne-0.0.
|
13
|
+
csc_cia_stne-0.0.17.dist-info/LICENCE,sha256=LPGMtgKki2C3KEZP7hDhA1HBrlq5JCHkIeStUCLEMx4,1073
|
14
|
+
csc_cia_stne-0.0.17.dist-info/METADATA,sha256=TicP94TngLb8-IYZOWavAHHq3tD0EUSs44vaPecK_8A,1003
|
15
|
+
csc_cia_stne-0.0.17.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
16
|
+
csc_cia_stne-0.0.17.dist-info/top_level.txt,sha256=ldo7GVv3tQx5KJvwBzdZzzQmjPys2NDVVn1rv0BOF2Q,13
|
17
|
+
csc_cia_stne-0.0.17.dist-info/RECORD,,
|
csc_cia_stne/cia_logging.py
DELETED
@@ -1,149 +0,0 @@
|
|
1
|
-
import logging
|
2
|
-
from rich.logging import RichHandler
|
3
|
-
from rich.theme import Theme
|
4
|
-
from rich.console import Console
|
5
|
-
import re
|
6
|
-
from pythonjsonlogger import jsonlogger
|
7
|
-
from rich.traceback import install
|
8
|
-
|
9
|
-
def logger(env:str = "local", log_level:str = "DEBUG"):
|
10
|
-
|
11
|
-
def get_log_level(log_level):
|
12
|
-
if log_level.upper().strip() == "DEBUG":
|
13
|
-
|
14
|
-
log_config_level = logging.DEBUG
|
15
|
-
|
16
|
-
elif log_level.upper().strip() == "INFO":
|
17
|
-
|
18
|
-
log_config_level = logging.INFO
|
19
|
-
|
20
|
-
elif log_level.upper().strip() == "WARNING":
|
21
|
-
|
22
|
-
log_config_level = logging.WARNING
|
23
|
-
|
24
|
-
elif log_level.upper().strip() == "ERROR":
|
25
|
-
|
26
|
-
log_config_level = logging.ERROR
|
27
|
-
|
28
|
-
elif log_level.upper().strip() == "CRITICAL":
|
29
|
-
|
30
|
-
log_config_level = logging.CRITICAL
|
31
|
-
|
32
|
-
else:
|
33
|
-
|
34
|
-
log_config_level = logging.INFO # ou outro nível padrão
|
35
|
-
|
36
|
-
return log_config_level
|
37
|
-
|
38
|
-
def add_log_level(level_name, level_num, method_name=None):
|
39
|
-
"""
|
40
|
-
Adiciona um log level
|
41
|
-
|
42
|
-
Parâmetros:
|
43
|
-
level_name (str): Nome do level
|
44
|
-
level_num (int): Número do level
|
45
|
-
"""
|
46
|
-
if not method_name:
|
47
|
-
|
48
|
-
method_name = level_name.lower()
|
49
|
-
|
50
|
-
if hasattr(logging, level_name):
|
51
|
-
|
52
|
-
raise AttributeError('{} already defined in logging module'.format(level_name))
|
53
|
-
|
54
|
-
if hasattr(logging, method_name):
|
55
|
-
|
56
|
-
raise AttributeError('{} already defined in logging module'.format(method_name))
|
57
|
-
|
58
|
-
if hasattr(logging.getLoggerClass(), method_name):
|
59
|
-
|
60
|
-
raise AttributeError('{} already defined in logger class'.format(method_name))
|
61
|
-
|
62
|
-
def log_for_level(self, message, *args, **kwargs):
|
63
|
-
|
64
|
-
if self.isEnabledFor(level_num):
|
65
|
-
|
66
|
-
self._log(level_num, message, args, **kwargs)
|
67
|
-
|
68
|
-
def log_to_root(message, *args, **kwargs):
|
69
|
-
|
70
|
-
logging.log(level_num, message, *args, **kwargs)
|
71
|
-
|
72
|
-
logging.addLevelName(level_num, level_name)
|
73
|
-
setattr(logging, level_name, level_num)
|
74
|
-
setattr(logging.getLoggerClass(), method_name, log_for_level)
|
75
|
-
setattr(logging, method_name, log_to_root)
|
76
|
-
|
77
|
-
add_log_level("SUCCESS",21)
|
78
|
-
|
79
|
-
if env.upper().strip() != "KARAVELA":
|
80
|
-
|
81
|
-
install()
|
82
|
-
|
83
|
-
# Definindo o tema customizado
|
84
|
-
custom_theme = Theme({
|
85
|
-
# python -m rich.color - cores
|
86
|
-
# python -m rich.default_styles - item + cor padrão
|
87
|
-
"logging.level.debug": "bold bright_cyan",
|
88
|
-
"logging.level.info": "bold bright_white",
|
89
|
-
"logging.level.warning": "bold orange1",
|
90
|
-
"logging.level.error": "bold red blink",
|
91
|
-
"logging.level.critical": "bold white on red blink",
|
92
|
-
"logging.level.success": "bold bright_green",
|
93
|
-
"log.time":"bold white",
|
94
|
-
"log.message":"bold gray70",
|
95
|
-
"repr.str":"dark_olive_green3",
|
96
|
-
"inspect.value.border":"blue",
|
97
|
-
})
|
98
|
-
|
99
|
-
console = Console(theme=custom_theme)
|
100
|
-
|
101
|
-
class CustomRichHandler(RichHandler):
|
102
|
-
def __init__(self, *args, rich_tracebacks=True, show_time=True, show_level=True, show_path=True, console=console, **kwargs):
|
103
|
-
super().__init__(rich_tracebacks=rich_tracebacks, show_time=show_time, show_level=show_level, show_path=show_path, console=console, *args, **kwargs)
|
104
|
-
self.show_time = show_time
|
105
|
-
|
106
|
-
def format(self, record: logging.LogRecord) -> str:
|
107
|
-
|
108
|
-
def remover_prefixo_log(mensagem):
|
109
|
-
# Expressão regular que encontra o padrão 'log_level:nivel: '
|
110
|
-
padrao = r'^(ERROR|WARNING|INFO|DEBUG|SUCCESS|CRITICAL):[^:]*:'
|
111
|
-
|
112
|
-
# Substitui o padrão encontrado por uma string vazia
|
113
|
-
return re.sub(padrao, '', mensagem).strip()
|
114
|
-
|
115
|
-
msg = f"| {record.getMessage()}"
|
116
|
-
|
117
|
-
return(str(msg))
|
118
|
-
|
119
|
-
# Configurando o logging com o CustomRichHandler
|
120
|
-
logging.basicConfig(
|
121
|
-
level=get_log_level(log_level),
|
122
|
-
handlers=[CustomRichHandler()],
|
123
|
-
datefmt="%d/%m/%Y %H:%M:%S |",
|
124
|
-
)
|
125
|
-
|
126
|
-
return logging.getLogger()
|
127
|
-
|
128
|
-
else:
|
129
|
-
|
130
|
-
def setup_json_logger():
|
131
|
-
logger = logging.getLogger()
|
132
|
-
logger.setLevel(get_log_level(log_level))
|
133
|
-
|
134
|
-
# Remove handlers anteriores, se houver
|
135
|
-
if logger.hasHandlers():
|
136
|
-
logger.handlers.clear()
|
137
|
-
|
138
|
-
log_handler = logging.StreamHandler()
|
139
|
-
formatter = jsonlogger.JsonFormatter(
|
140
|
-
fmt='%(asctime)s %(levelname)s %(name)s %(message)s %(pathname)s %(lineno)d %(exc_info)s %(stack_info)s %(funcName)s %(module)s',
|
141
|
-
json_ensure_ascii=False
|
142
|
-
)
|
143
|
-
log_handler.setFormatter(formatter)
|
144
|
-
logger.addHandler(log_handler)
|
145
|
-
|
146
|
-
return logger
|
147
|
-
|
148
|
-
# Chama a função para configurar o logger
|
149
|
-
return setup_json_logger()
|
File without changes
|
File without changes
|
File without changes
|