-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (74 loc) · 2.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* used to stream logs to elasticsearch server
* @param {Object} config {
* service
* host
* env
* }
*
* @returns {Logger} {
* info: Function,
* error: Function
* }
*/
const shieldfyLogger = (config = {}) => {
let { service, host = process.env.ELASTICSEARCH_HOST, env = process.env.APP_ENV } = config
// throw err if no service name
if (!service) throw new Error('service name is required')
// throw err if no host param and no ELASTICSEARCH_HOST in env
if (!host && !process.env.ELASTICSEARCH_HOST) throw new Error('trying to use process.env.ELASTICSEARCH_HOST as host failed')
const winston = require('winston');
const Elasticsearch = require('winston-elasticsearch');
// creating winston transport console instance
const winstonTransportConsole = new winston.transports.Console({ level: 'info', format: winston.format.simple() })
// logger
winston.configure({
level: 'info',
format: winston.format.json(),
transports: [
winstonTransportConsole //log on console
],
exitOnError: false // without it winston stops login after the first uncaught exception
});
/**
* in case of local or test environment or no env at all
*/
if (!env || env === 'local' || env === 'test') return winston
// elastic search config
const esTransportOpts = {
level: 'info',
clientOpts: {
host: host,
log: "info"
},
transformer: logData => {
const transformedData = {
"@timestamp": new Date().toISOString(),
severity: logData.level,
service: service,
environment: env,
message: `${logData.message}`,
fields: {}
}
return transformedData
}
};
// creating es instance
const es = new Elasticsearch(esTransportOpts)
// adiing close the es functionality
// usefull in case of a lambda function
winston.close = () => es.bulkWriter.schedule = () => { };
// creating winston transport file instance
const winstonTransportFile = new winston.transports.File({ filename: "logfile.log", level: 'error' })
/**
* in case of non local or test environment
* add the elasticsearch log
* add the file log
* and remove the console log
*/
winston.add(es);
winston.add(winstonTransportFile);
winston.remove(winstonTransportConsole);
return winston
}
module.exports = shieldfyLogger