le mie informazioni di contatto
Posta[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Questa è una continuazione dell'articolo precedente "Elasticsearch: registrazione ECS Node.js - Pino” continuazione di Continuiamo l'articolo precedente per parlare dell'utilizzo del pacchetto Winston come target Node.js L'applicazione genera ECS per abbinare il giorno.Questo pacchetto Node.js lo èWinston LoggerViene fornito un formattatore Registrazione Elastic Common Schema (ECS). compatibile.combinareBattito di file Mittente, puoi monitorare tutti i log da un'unica posizione nell'Elastic Stack. Supporta la versione Winston 3.x >=3.3.3.
- npm install @elastic/ecs-winston-format
- npm install winston
winston-registrazione.js
- const winston = require('winston');
- const { ecsFormat } = require('@elastic/ecs-winston-format');
-
- const logger = winston.createLogger({
- format: ecsFormat(/* options */), // 1
- transports: [
- new winston.transports.Console()
- ]
- });
-
- logger.info('hi');
- logger.error('oops there is a problem', { err: new Error('boom') });
Il risultato dell'esecuzione del codice sopra è:
Versione 7.16+
filebeat.yml
- filebeat.inputs:
- - type: filestream # 1
- paths: /path/to/logs.json
- parsers:
- - ndjson:
- overwrite_keys: true # 2
- add_error_key: true # 3
- expand_keys: true # 4
-
- processors: // 5
- - add_host_metadata: ~
- - add_cloud_metadata: ~
- - add_docker_metadata: ~
- - add_kubernetes_metadata: ~
Battito di file < 7.16
filebeat.yml
- filebeat.inputs:
- - type: log
- paths: /path/to/logs.json
- json.keys_under_root: true
- json.overwrite_keys: true
- json.add_error_key: true
- json.expand_keys: true
-
- processors:
- - add_host_metadata: ~
- - add_cloud_metadata: ~
- - add_docker_metadata: ~
- - add_kubernetes_metadata: ~
Per ulteriori informazioni, vedere Riferimento a Filebeat。
winston-registrazione.js
- const winston = require('winston');
- const { ecsFormat } = require('@elastic/ecs-winston-format');
-
- const logger = winston.createLogger({
- level: 'info',
- format: ecsFormat(/* options */), // 1
- transports: [
- new winston.transports.Console()
- ]
- });
-
- logger.info('hi');
- logger.error('oops there is a problem', { foo: 'bar' });
node winston-logging.js | jq .
Esegui questo script (disponibile suQuiottenuto) produrrà un output di registro simile al precedente.
Il formattatore è responsabile della serializzazione dei dati in JSON, quindi non è necessario aggiungere json Formattatore.Inoltre, il formattatore genera automaticamente il timestamp, quindi non è necessario aggiungerlomarca temporale Formattatore.
Per impostazione predefinita, il formattatore converte il metacampo err di un'istanza Error in Campo ECSError .Per esempioesempio:
winston-registrazione.js
- const winston = require('winston');
- const { ecsFormat } = require('@elastic/ecs-winston-format');
- const logger = winston.createLogger({
- format: ecsFormat(),
- transports: [
- new winston.transports.Console()
- ]
- });
-
- const myErr = new Error('boom');
- logger.info('oops', { err: myErr });
La gestione speciale del metacampo err può essere disabilitata tramite l'opzione convertErr: false:
winston-registrazione.js
- const winston = require('winston');
- const { ecsFormat } = require('@elastic/ecs-winston-format');
- const logger = winston.createLogger({
- format: ecsFormat({convertErr: false} ),
- transports: [
- new winston.transports.Console()
- ]
- });
-
- const myErr = new Error('boom');
- logger.info('oops', { err: myErr });
Utilizzando l'opzione convertReqRes: true, il formattatore convertirà automaticamente il core Node.js quando viene passato rispettivamente come metafield req e res. richiesta Erisposta oggetto.
winston-registrazione.js
- const http = require('http');
- const winston = require('winston');
- const { ecsFormat } = require('@elastic/ecs-winston-format');
-
- const logger = winston.createLogger({
- level: 'info',
- format: ecsFormat({ convertReqRes: true }), // 1
- transports: [
- new winston.transports.Console()
- ]
- });
-
- const server = http.createServer(handler);
- server.listen(3000, () => {
- logger.info('listening at http://localhost:3000')
- });
-
- function handler (req, res) {
- res.setHeader('Foo', 'Bar');
- res.end('ok');
- logger.info('handled request', { req, res }); // 2
- }
Questo utilizzerà Campi HTTP ECS Genera un registro contenente informazioni sulla richiesta e sulla risposta.Per esempioesempio:
Sopra, dobbiamo accedere http://localhost:3000 Solo allora potrai vedere le informazioni sul giorno mostrate sopra.
Questo ECS formattatore di log conAPM elastico integrato.Se l'applicazione Node utilizzaAgente APM elastico Node.js, vengono aggiunti diversi campi al record di log per correlare il servizio APM o tracciare e registrare i dati:
Ad esempio, corri esempi/http-con-elastic-apm.js Ecurl -i localhost:3000/ Viene prodotto un record di registro contenente il seguente contenuto:
- % node examples/http-with-elastic-apm.js | jq .
- ...
- "service.name": "http-with-elastic-apm",
- "service.version": "1.4.0",
- "service.environment": "development",
- "event.dataset": "http-with-elastic-apm"
- "trace.id": "7fd75f0f33ff49aba85d060b46dcad7e",
- "transaction.id": "6c97c7c1b468fa05"
- }
Questi ID corrispondono ai dati di tracciamento riportati dall'agente APM.
L'integrazione con Elastic APM può essere disabilitata esplicitamente tramite l'opzione apmIntegration: false, ad esempio:
- const logger = winston.createLogger({
- format: ecsFormat({ apmIntegration: false }),
- // ...
- })
specifica di registrazione ecs Si consiglia che i primi tre campi nel record di log siano @timestamp, log.level e message. A partire dalla versione 1.5.0, questo formattatore non segue questa raccomandazione. Ciò è possibile ma richiede la creazione di un nuovo oggetto in ecsFields per ogni record di log. Dato che l'ordine dei campi di registrazione ecs è finalizzato alla leggibilità e non influisce sull'interoperabilità, si è deciso di dare priorità alle prestazioni.
Crea un formattatore per Winston che emetta il formato di registrazione ECS.Questo è un trattamentoecsFields([opzioni]) EecsStringify([opzioni]) formato unico. I due seguenti sono equivalenti:
- const { ecsFormat, ecsFields, ecsStringify } = require('@elastic/ecs-winston-format');
- const winston = require('winston');
-
- const logger = winston.createLogger({
- format: ecsFormat(/* options */),
- // ...
- });
-
- const logger = winston.createLogger({
- format: winston.format.combine(
- ecsFields(/* options */),
- ecsStringify()
- ),
- // ...
- });
Creare un formattatore per Winston che converta i campi sull'oggetto delle informazioni di registrazione nel formato di registrazione ECS.
Crea un formattatore per Winston per stringere/serializzare i record di log in JSON.
Questo è simile a logform.json(). Entrambi utilizzano il pacchetto safe-stable-stringify per generare JSON. Alcune differenze: