csc-cia-stne 0.0.14__py3-none-any.whl → 0.0.16__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 CHANGED
@@ -1,7 +1,11 @@
1
+ import os
2
+ if os.getenv('ambiente_de_execucao') is not None and os.getenv('ambiente_de_execucao') == "karavela":
3
+ from .logger_json import logger
4
+ else:
5
+ from .logger_rich import logger
1
6
  from .karavela import Karavela
2
7
  from .utilitarios import Util
3
8
  from .servicenow import ServiceNow
4
- from .cia_logging import logger
5
9
  from .stne_admin import StoneAdmin
6
10
  from .bc_sta import BC_STA
7
11
  from .bc_correios import BC_Correios
@@ -34,7 +34,7 @@ class BigQuery():
34
34
 
35
35
  try:
36
36
 
37
- if(creds_dict not None):
37
+ if(creds_dict is not None):
38
38
 
39
39
  credentials = service_account.Credentials.from_service_account_info(
40
40
  creds_dict,
@@ -0,0 +1,36 @@
1
+ import logging
2
+ from pythonjsonlogger import jsonlogger
3
+
4
+ def setup_json_logger():
5
+ logger = logging.getLogger()
6
+ logger.setLevel(logging.INFO)
7
+
8
+ # Remove handlers anteriores, se houver
9
+ if logger.hasHandlers():
10
+ logger.handlers.clear()
11
+
12
+ log_handler = logging.StreamHandler()
13
+ formatter = jsonlogger.JsonFormatter(
14
+ fmt='%(asctime)s %(levelname)s %(name)s %(message)s %(pathname)s %(lineno)d %(exc_info)s %(stack_info)s %(funcName)s %(module)s',
15
+ json_ensure_ascii=False
16
+ )
17
+ log_handler.setFormatter(formatter)
18
+ logger.addHandler(log_handler)
19
+
20
+ # Capturando logs da biblioteca FastAPI/Uvicorn
21
+ #uvicorn_logger = logging.getLogger("uvicorn")
22
+ #uvicorn_logger.handlers = logger.handlers
23
+ #uvicorn_logger.setLevel(logging.INFO)
24
+
25
+ #uvicorn_error_logger = logging.getLogger("uvicorn.error")
26
+ #uvicorn_error_logger.handlers = logger.handlers
27
+ #uvicorn_error_logger.setLevel(logging.INFO)
28
+
29
+ #uvicorn_access_logger = logging.getLogger("uvicorn.access")
30
+ #uvicorn_access_logger.handlers = logger.handlers
31
+ #uvicorn_access_logger.setLevel(logging.INFO)
32
+
33
+ return logger
34
+
35
+ # Chama a função para configurar o logger
36
+ logger = setup_json_logger()
@@ -0,0 +1,109 @@
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
+ import traceback
7
+ import os
8
+
9
+ # Definindo o nível de log baseado nas configurações
10
+ if os.getenv('log_level') is None:
11
+
12
+ log_config_level = logging.DEBUG
13
+
14
+ elif os.getenv('log_level') == "DEBUG":
15
+
16
+ log_config_level = logging.DEBUG
17
+
18
+ elif os.getenv('log_level') == "INFO":
19
+
20
+ log_config_level = logging.INFO
21
+
22
+ else:
23
+
24
+ log_config_level = logging.WARNING # ou outro nível padrão
25
+
26
+ # Definindo o tema customizado
27
+ custom_theme = Theme({
28
+ # python -m rich.color - cores
29
+ # python -m rich.default_styles - item + cor padrão
30
+ "logging.level.debug": "bold bright_cyan",
31
+ "logging.level.info": "bold bright_white",
32
+ "logging.level.warning": "bold orange1",
33
+ "logging.level.error": "bold red blink",
34
+ "logging.level.critical": "bold white on red blink",
35
+ "logging.level.success": "bold bright_green",
36
+ "log.time":"bold white",
37
+ "log.message":"bold gray70",
38
+ "repr.str":"dark_olive_green3",
39
+ "inspect.value.border":"blue",
40
+ })
41
+
42
+ console = Console(theme=custom_theme)
43
+
44
+ class CustomRichHandler(RichHandler):
45
+ def __init__(self, *args, rich_tracebacks=True, show_time=True, show_level=True, show_path=True, console=console, omit_repeated_times=True, **kwargs):
46
+ super().__init__(rich_tracebacks=rich_tracebacks, show_time=show_time, show_level=show_level, show_path=show_path, console=console, omit_repeated_times=omit_repeated_times, *args, **kwargs)
47
+ self.show_time = show_time
48
+
49
+
50
+ def format(self, record: logging.LogRecord) -> str:
51
+ try:
52
+ msg = f"| {record.getMessage()}"
53
+ #msg = f"{record.getMessage()}"
54
+
55
+ return(str(msg))
56
+ except Exception as e:
57
+ print("FALHA AO FORMATAR O LOG")
58
+ print(e)
59
+
60
+ # Configurando o logging com o CustomRichHandler
61
+ logging.basicConfig(
62
+ level=log_config_level,
63
+ handlers=[CustomRichHandler()],
64
+ datefmt="%d/%m/%Y %H:%M:%S |",
65
+ format="| %(message)s"
66
+ )
67
+
68
+ def add_log_level(level_name, level_num, method_name=None):
69
+ """
70
+ Adiciona um log level
71
+
72
+ Parâmetros:
73
+ level_name (str): Nome do level
74
+ level_num (int): Número do level
75
+ """
76
+ if not method_name:
77
+
78
+ method_name = level_name.lower()
79
+
80
+ if hasattr(logging, level_name):
81
+
82
+ raise AttributeError('{} already defined in logging module'.format(level_name))
83
+
84
+ if hasattr(logging, method_name):
85
+
86
+ raise AttributeError('{} already defined in logging module'.format(method_name))
87
+
88
+ if hasattr(logging.getLoggerClass(), method_name):
89
+
90
+ raise AttributeError('{} already defined in logger class'.format(method_name))
91
+
92
+ def log_for_level(self, message, *args, **kwargs):
93
+
94
+ if self.isEnabledFor(level_num):
95
+
96
+ self._log(level_num, message, args, **kwargs)
97
+
98
+ def log_to_root(message, *args, **kwargs):
99
+
100
+ logging.log(level_num, message, *args, **kwargs)
101
+
102
+ logging.addLevelName(level_num, level_name)
103
+ setattr(logging, level_name, level_num)
104
+ setattr(logging.getLoggerClass(), method_name, log_for_level)
105
+ setattr(logging, method_name, log_to_root)
106
+
107
+ add_log_level("SUCCESS",21)
108
+
109
+ logger = logging.getLogger()
@@ -0,0 +1,47 @@
1
+ from pydantic_settings import BaseSettings
2
+ from pydantic import ValidationError
3
+ from rich.traceback import install
4
+ from dotenv import load_dotenv
5
+
6
+ # Instala formatações de exception da biblioteca Rich
7
+ install()
8
+
9
+ # Carrega .env
10
+ load_dotenv()
11
+
12
+ # Classe para armazenar configurações
13
+ class Settings(BaseSettings):
14
+ # Ambiente de Execução
15
+ ambiente_de_execucao: str = "local"
16
+ log_level: str = "DEBUG"
17
+
18
+ # Titulo
19
+ project_name: str
20
+ project_version: str
21
+ project_dev_name: str
22
+ project_dev_mail: str
23
+
24
+ class Config:
25
+ env_file = ".env"
26
+ env_file_encoding = 'utf-8' # Defina a codificação se necessário
27
+
28
+ # Carrega as configurações do arquivo .env ou retorna exception com os campos obrigatórios que não foram preenchidos
29
+ def load_settings():
30
+ try:
31
+ settings = Settings()
32
+ return settings
33
+
34
+ except ValidationError as e:
35
+ # Extrair os detalhes da exceção
36
+ errors = e.errors()
37
+ missing_vars = [error['loc'][0] for error in errors if error['type'] == 'missing']
38
+
39
+ # Criar uma mensagem personalizada
40
+ if missing_vars:
41
+ missing_vars_str = ', '.join(missing_vars)
42
+ raise ValueError(
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
+ "Outras variáveis, não obrigatórias: 'ambiente_de_execução' ('local' ou 'karavela') e 'log_level' ('DEBUG', 'INFO', etc)"
45
+ )
46
+
47
+ settings = load_settings()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: csc_cia_stne
3
- Version: 0.0.14
3
+ Version: 0.0.16
4
4
  Summary: Biblioteca do time CSC-CIA utilizada no desenvolvimento de RPAs
5
5
  License: MIT
6
6
  Keywords: karavela,csc,cia,stone,rpa
@@ -10,12 +10,14 @@ Requires-Dist: python-json-logger
10
10
  Requires-Dist: rich
11
11
  Requires-Dist: requests
12
12
  Requires-Dist: pydantic
13
+ Requires-Dist: pydantic-settings
13
14
  Requires-Dist: zeep
14
15
  Requires-Dist: google-cloud-bigquery
15
16
  Requires-Dist: google-cloud-storage
16
17
  Requires-Dist: google-auth-oauthlib
17
18
  Requires-Dist: google-auth-httplib2
18
19
  Requires-Dist: pyjwt
20
+ Requires-Dist: python-dotenv
19
21
 
20
22
  Essa biblioteca é desenvolvida e atualizada pelo time **CSC-CIA** da **Stone**
21
23
 
@@ -0,0 +1,16 @@
1
+ csc_cia_stne/__init__.py,sha256=9nxsvJIoD5osa_3qM93HtCjvKJV3c01DhdUixrrYZ-Q,419
2
+ csc_cia_stne/bc_correios.py,sha256=ANsvLyL7wdkM0MvjjBHB2Ih4eyTcyWgt5IqiK0Rv89E,23014
3
+ csc_cia_stne/bc_sta.py,sha256=I9N29wjTbd4ZmoM2yIW-xp3X-dMENZdSb0JhapfCegY,10988
4
+ csc_cia_stne/gcp_bigquery.py,sha256=f8UEQgr6XyFacYX0bRq4UDmWoH-0XqZF8fA2LsLTtAU,5654
5
+ csc_cia_stne/karavela.py,sha256=Q7MbQXXz_jtrLHM7QeenbSzcro07EpoFk4lKglivJ_I,3564
6
+ csc_cia_stne/logger_json.py,sha256=2G0rm0lyCtHn4o2v7fzn4wMylb0A_nbxiQatnrSZxHs,1212
7
+ csc_cia_stne/logger_rich.py,sha256=LU6VGnus-1tPmdacuIphTDxxfQU0Uvl68BKVKLDuHzg,3290
8
+ csc_cia_stne/servicenow.py,sha256=vSsNSANFyCZtDu2O7YmdoCbr-_bO1sgMWnOI29mFBOA,23311
9
+ csc_cia_stne/settings.py,sha256=Xr3TPnlGjS_WZ01VeHXUy1p9m1GdA-OUJ8HEA8t_hlU,1561
10
+ csc_cia_stne/stne_admin.py,sha256=G5ozXt18VjKL2BHtROQk4GnfVY1xM14RXSQ-rra_D54,15487
11
+ csc_cia_stne/utilitarios.py,sha256=LU8YrELiRIW4UxqULjiUPYmgbEx79NGenK5QKRdSh_E,2050
12
+ csc_cia_stne-0.0.16.dist-info/LICENCE,sha256=LPGMtgKki2C3KEZP7hDhA1HBrlq5JCHkIeStUCLEMx4,1073
13
+ csc_cia_stne-0.0.16.dist-info/METADATA,sha256=oglzzagHj7-ZWSQvATgcTO1HkZ5zVId-_gXrWuoZu48,1003
14
+ csc_cia_stne-0.0.16.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
15
+ csc_cia_stne-0.0.16.dist-info/top_level.txt,sha256=ldo7GVv3tQx5KJvwBzdZzzQmjPys2NDVVn1rv0BOF2Q,13
16
+ csc_cia_stne-0.0.16.dist-info/RECORD,,
@@ -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()
@@ -1,14 +0,0 @@
1
- csc_cia_stne/__init__.py,sha256=VYD8Lj4LgMqM5d3f2dgS5oqThEo9czi-wIDPaw3b3Ec,261
2
- csc_cia_stne/bc_correios.py,sha256=ANsvLyL7wdkM0MvjjBHB2Ih4eyTcyWgt5IqiK0Rv89E,23014
3
- csc_cia_stne/bc_sta.py,sha256=I9N29wjTbd4ZmoM2yIW-xp3X-dMENZdSb0JhapfCegY,10988
4
- csc_cia_stne/cia_logging.py,sha256=GbxpcjtF_7tiRez2awIKZJXdo5CvM0n_mo1RKpfvAnU,5100
5
- csc_cia_stne/gcp_bigquery.py,sha256=GBI7BDyranwr4IQGzLbbZRgD2Km6tlkqqVCI3R89-bE,5651
6
- csc_cia_stne/karavela.py,sha256=Q7MbQXXz_jtrLHM7QeenbSzcro07EpoFk4lKglivJ_I,3564
7
- csc_cia_stne/servicenow.py,sha256=vSsNSANFyCZtDu2O7YmdoCbr-_bO1sgMWnOI29mFBOA,23311
8
- csc_cia_stne/stne_admin.py,sha256=G5ozXt18VjKL2BHtROQk4GnfVY1xM14RXSQ-rra_D54,15487
9
- csc_cia_stne/utilitarios.py,sha256=LU8YrELiRIW4UxqULjiUPYmgbEx79NGenK5QKRdSh_E,2050
10
- csc_cia_stne-0.0.14.dist-info/LICENCE,sha256=LPGMtgKki2C3KEZP7hDhA1HBrlq5JCHkIeStUCLEMx4,1073
11
- csc_cia_stne-0.0.14.dist-info/METADATA,sha256=nkzD0SKfI5NrGRzN3si5tx4JbcPSPXSWTUwCsFa2mMo,941
12
- csc_cia_stne-0.0.14.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
13
- csc_cia_stne-0.0.14.dist-info/top_level.txt,sha256=ldo7GVv3tQx5KJvwBzdZzzQmjPys2NDVVn1rv0BOF2Q,13
14
- csc_cia_stne-0.0.14.dist-info/RECORD,,