azify-logger 1.0.4 → 1.0.8

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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Sistema de logging centralizado com OpenTelemetry e OpenSearch para múltiplas a
8
8
 
9
9
  | Ambiente | URL |
10
10
  |----------|-------------------------------------------------------|
11
- | **Development** | `http://localhost:3001` |
11
+ | **Development** | `http://localhost:3001/log` |
12
12
  | **Staging** | `https://logsdashboard.azify.dev/send` |
13
13
  | **Production** | `https://logsdashboard.azify.prd/send` (a configurar) |
14
14
 
@@ -82,20 +82,20 @@ const app = express()
82
82
 
83
83
  ## ⚙️ Variáveis de Ambiente
84
84
 
85
- | Variável | Padrão | Descrição |
86
- |----------|-------|-----------|
87
- | `APP_NAME` | - | Nome da aplicação |
88
- | `AZIFY_LOGGER_URL` | `http://localhost:3001` | URL do logger |
85
+ | Variável | Padrão | Descrição |
86
+ |----------|-----------------------------------|-----------|
87
+ | `APP_NAME` | - | Nome da aplicação |
88
+ | `AZIFY_LOGGER_URL` | `http://localhost:3001/log` | URL do logger |
89
89
  | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318/v1/traces` | OTLP endpoint |
90
- | `NODE_ENV` | `development` | Ambiente |
91
- | `AZIFY_LOGGER_AUTOREG_DISABLE` | `""` | Se `"1"`, desativa auto-registro do OTEL |
90
+ | `NODE_ENV` | `development` | Ambiente |
91
+ | `AZIFY_LOGGER_AUTOREG_DISABLE` | `""` | Se `"1"`, desativa auto-registro do OTEL |
92
92
 
93
93
  ### 🌐 URLs por Ambiente
94
94
 
95
95
  **Desenvolvimento (Local):**
96
96
  ```env
97
97
  APP_NAME=minha-app
98
- AZIFY_LOGGER_URL=http://localhost:3001
98
+ AZIFY_LOGGER_URL=http://localhost:3001/log
99
99
  NODE_ENV=development
100
100
  ```
101
101
 
@@ -118,7 +118,7 @@ NODE_ENV=production
118
118
  Apenas se estiver usando Docker Compose com rede compartilhada:
119
119
 
120
120
  ```env
121
- AZIFY_LOGGER_URL=http://azify-logger:3001
121
+ AZIFY_LOGGER_URL=http://azify-logger:3001/log
122
122
  ```
123
123
 
124
124
  ### Docker e Node antigos
@@ -165,7 +165,7 @@ if (createAzifyBunyanStream) {
165
165
  level: 'info',
166
166
  type: 'raw',
167
167
  stream: createAzifyBunyanStream({
168
- loggerUrl: process.env.AZIFY_LOGGER_URL || 'http://localhost:3001',
168
+ loggerUrl: process.env.AZIFY_LOGGER_URL || 'http://localhost:3001/log',
169
169
  serviceName: process.env.APP_NAME || 'app'
170
170
  })
171
171
  })
@@ -193,7 +193,7 @@ const { streams } = require('azify-logger')
193
193
  const pino = require('pino')
194
194
 
195
195
  const logger = pino({ level: 'info' }, streams.createPinoStream({
196
- loggerUrl: 'http://localhost:3001',
196
+ loggerUrl: 'http://localhost:3001/log',
197
197
  serviceName: 'nome-app'
198
198
  }))
199
199
 
@@ -207,7 +207,7 @@ const { createAzifyLogger } = require('azify-logger')
207
207
 
208
208
  const logger = createAzifyLogger({
209
209
  serviceName: 'nome-app',
210
- loggerUrl: 'http://localhost:3001'
210
+ loggerUrl: 'http://localhost:3001/log'
211
211
  })
212
212
 
213
213
  logger.info('Mensagem', { userId: '123' })
@@ -232,7 +232,7 @@ Aguarde alguns minutos. Você verá:
232
232
  ✅ Tudo pronto!
233
233
  📊 OpenSearch: http://localhost:9200
234
234
  🎨 OpenSearch Dashboards: http://localhost:5601
235
- 📝 Logger API: http://localhost:3001
235
+ 📝 Logger API: http://localhost:3001/log
236
236
  🔭 OTEL Collector: http://localhost:4318
237
237
  ```
238
238
 
package/index.js CHANGED
@@ -8,7 +8,18 @@ if (process.env.AZIFY_LOGGER_AUTOREG_DISABLE !== '1') {
8
8
  try { require('./register-restify') } catch (_) {}
9
9
  }
10
10
 
11
+ /**
12
+ * AzifyLogger class for structured logging with OpenTelemetry integration
13
+ * @class
14
+ */
11
15
  class AzifyLogger {
16
+ /**
17
+ * Creates an instance of AzifyLogger
18
+ * @param {Object} options - Configuration options
19
+ * @param {string} [options.serviceName='azipay'] - Name of the service
20
+ * @param {string} [options.loggerUrl='http://localhost:3001'] - URL of the azify-logger service
21
+ * @param {string} [options.environment] - Environment name (defaults to NODE_ENV or 'development')
22
+ */
12
23
  constructor(options = {}) {
13
24
  this.options = {
14
25
  serviceName: options.serviceName || 'azipay',
@@ -21,6 +32,13 @@ class AzifyLogger {
21
32
  propagation.setGlobalPropagator(this.propagator)
22
33
  }
23
34
 
35
+ /**
36
+ * Sends a log entry to the azify-logger service
37
+ * @param {string} level - Log level (info, error, warn, debug)
38
+ * @param {string} message - Log message
39
+ * @param {Object} [meta={}] - Additional metadata to include in the log
40
+ * @returns {Promise<void>}
41
+ */
24
42
  async log(level, message, meta = {}) {
25
43
  const span = trace.getSpan(context.active())
26
44
  const spanContext = span?.spanContext()
@@ -64,10 +82,23 @@ class AzifyLogger {
64
82
  }
65
83
  }
66
84
 
85
+ /**
86
+ * Logs an info level message
87
+ * @param {string} message - Log message
88
+ * @param {Object} [meta={}] - Additional metadata
89
+ * @returns {Promise<void>}
90
+ */
67
91
  info(message, meta = {}) {
68
92
  return this.log('info', message, meta)
69
93
  }
70
94
 
95
+ /**
96
+ * Logs an error level message with optional error object
97
+ * @param {string} message - Log message
98
+ * @param {Error} [error=null] - Error object to include in metadata
99
+ * @param {Object} [meta={}] - Additional metadata
100
+ * @returns {Promise<void>}
101
+ */
71
102
  error(message, error = null, meta = {}) {
72
103
  const logMeta = { ...meta }
73
104
  if (error) {
@@ -80,19 +111,49 @@ class AzifyLogger {
80
111
  return this.log('error', message, logMeta)
81
112
  }
82
113
 
114
+ /**
115
+ * Logs a warning level message
116
+ * @param {string} message - Log message
117
+ * @param {Object} [meta={}] - Additional metadata
118
+ * @returns {Promise<void>}
119
+ */
83
120
  warn(message, meta = {}) {
84
121
  return this.log('warn', message, meta)
85
122
  }
86
123
 
124
+ /**
125
+ * Logs a debug level message
126
+ * @param {string} message - Log message
127
+ * @param {Object} [meta={}] - Additional metadata
128
+ * @returns {Promise<void>}
129
+ */
87
130
  debug(message, meta = {}) {
88
131
  return this.log('debug', message, meta)
89
132
  }
90
133
  }
91
134
 
135
+ /**
136
+ * Creates a new AzifyLogger instance with custom options
137
+ * @param {Object} options - Configuration options
138
+ * @param {string} [options.serviceName] - Name of the service
139
+ * @param {string} [options.loggerUrl] - URL of the azify-logger service
140
+ * @param {string} [options.environment] - Environment name
141
+ * @returns {AzifyLogger} New AzifyLogger instance
142
+ * @example
143
+ * const logger = createAzifyLogger({ serviceName: 'my-app' });
144
+ * logger.info('Hello world');
145
+ */
92
146
  function createAzifyLogger(options = {}) {
93
147
  return new AzifyLogger(options)
94
148
  }
95
149
 
150
+ /**
151
+ * Creates a new AzifyLogger instance using environment variables
152
+ * @returns {AzifyLogger} New AzifyLogger instance configured from environment
153
+ * @example
154
+ * const logger = createAzifyLoggerFromEnv();
155
+ * logger.info('Hello world');
156
+ */
96
157
  function createAzifyLoggerFromEnv() {
97
158
  return createAzifyLogger({
98
159
  serviceName: process.env.APP_NAME || 'azipay',
@@ -1,6 +1,17 @@
1
1
  const axios = require('axios')
2
2
  const { als, runWithRequestContext, startRequestContext, getRequestContext } = require('./store')
3
3
 
4
+ /**
5
+ * Creates an Express middleware for automatic request/response logging with azify-logger
6
+ * @param {Object} options - Configuration options
7
+ * @param {string} [options.serviceName] - Name of the service (defaults to APP_NAME env var or 'assemble')
8
+ * @param {string} [options.loggerUrl] - URL of the azify-logger service (defaults to AZIFY_LOGGER_URL env var or 'http://localhost:3001')
9
+ * @param {string} [options.environment] - Environment name (defaults to NODE_ENV env var or 'development')
10
+ * @returns {Function} Express middleware function
11
+ * @example
12
+ * const azifyMiddleware = require('azify-logger/middleware-express');
13
+ * app.use(azifyMiddleware({ serviceName: 'my-app' }));
14
+ */
4
15
  function createExpressLoggingMiddleware(options = {}) {
5
16
  const config = {
6
17
  serviceName: options.serviceName || process.env.APP_NAME || 'assemble',
@@ -8,6 +19,13 @@ function createExpressLoggingMiddleware(options = {}) {
8
19
  environment: options.environment || process.env.NODE_ENV || 'development'
9
20
  }
10
21
 
22
+ /**
23
+ * Sends a log entry to the azify-logger service
24
+ * @param {string} level - Log level (info, error, warn, debug)
25
+ * @param {string} message - Log message
26
+ * @param {Object} [meta={}] - Additional metadata to include in the log
27
+ * @private
28
+ */
11
29
  async function sendLog(level, message, meta = {}) {
12
30
  const logData = {
13
31
  level,
@@ -25,12 +43,21 @@ function createExpressLoggingMiddleware(options = {}) {
25
43
  }
26
44
 
27
45
  try {
28
- await axios.post(`${config.loggerUrl}/log`, logData, {
46
+ await axios.post(`${config.loggerUrl}`, logData, {
29
47
  timeout: 5000
30
48
  })
31
- } catch (error) {}
49
+ } catch (error) {
50
+ console.error('Erro ao enviar log:', error.message)
51
+ }
32
52
  }
33
53
 
54
+ /**
55
+ * Express middleware function that logs requests and responses
56
+ * @param {Object} req - Express request object
57
+ * @param {Object} res - Express response object
58
+ * @param {Function} next - Express next function
59
+ * @returns {void}
60
+ */
34
61
  return function azifyExpressLoggingMiddleware(req, res, next) {
35
62
  const startTime = Date.now()
36
63
  const requestId = req.requestId || require('uuid').v4()
@@ -58,10 +85,10 @@ function createExpressLoggingMiddleware(options = {}) {
58
85
  url: req.url,
59
86
  baseUrl: baseUrl,
60
87
  path: req.url,
61
- headers: req.headers,
62
- query: req.query,
63
- userAgent: req.headers['user-agent'],
64
- ip: req.connection?.remoteAddress || req.socket?.remoteAddress || req.ip,
88
+ headers: req.headers || {},
89
+ query: req.query || {},
90
+ userAgent: req.headers?.['user-agent'] || 'unknown',
91
+ ip: req.connection?.remoteAddress || req.socket?.remoteAddress || req.ip || 'unknown',
65
92
  traceId: requestTraceId,
66
93
  spanId: requestSpanId,
67
94
  parentSpanId: requestParentSpanId
@@ -204,6 +231,10 @@ function createExpressLoggingMiddleware(options = {}) {
204
231
  originalEnd.call(this, chunk, encoding)
205
232
  }
206
233
 
234
+ /**
235
+ * Logs the response data to azify-logger
236
+ * @private
237
+ */
207
238
  function logResponse() {
208
239
  const duration = Date.now() - startTime
209
240
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "azify-logger",
3
- "version": "1.0.4",
3
+ "version": "1.0.8",
4
4
  "description": "Azify Logger Client - Centralized logging for OpenSearch",
5
5
  "main": "index.js",
6
6
  "type": "commonjs",
@@ -26,7 +26,7 @@
26
26
  "author": "Azify",
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
- "@opentelemetry/api": ">=1.0.0 <2.0.0",
29
+ "@opentelemetry/api": "^1.7.0",
30
30
  "@opentelemetry/auto-instrumentations-node": "^0.40.0",
31
31
  "@opentelemetry/core": "^1.28.0",
32
32
  "@opentelemetry/exporter-trace-otlp-http": "^0.45.0",
package/server.js CHANGED
@@ -32,6 +32,11 @@ const propagator = new W3CTraceContextPropagator()
32
32
 
33
33
  const traceContextMap = new Map()
34
34
 
35
+ /**
36
+ * Ensures the OpenSearch index exists and is properly configured
37
+ * @returns {Promise<void>}
38
+ * @private
39
+ */
35
40
  async function ensureIndex() {
36
41
  const indexName = 'logs-azify'
37
42
  const osUrl = process.env.OPENSEARCH_URL || 'http://localhost:9200'