-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
applicationinsights.js
96 lines (84 loc) · 2.8 KB
/
applicationinsights.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
87
88
89
90
91
92
93
94
95
96
'use strict'
const appInsights = require('applicationinsights')
const stream = require('stream')
class Client {
constructor (options = {}) {
if (options.setup) {
options.setup(appInsights)
} else {
const iKey = options.key || process.env.APPINSIGHTS_INSTRUMENTATIONKEY
appInsights.setup(iKey).start()
}
this.insights = appInsights.defaultClient
}
getLogException (item) {
if (item.level !== 50 || item.type !== 'Error') { return }
const err = new Error(item.msg)
err.stack = item.stack || ''
return err
}
getLogMessage (item) {
if (item.msg) { return item.msg }
const severity = this.getLogSeverity(item.level)
return this.getLogSeverityName(severity)
}
getLogProperties (item) {
const props = Object.assign({}, item)
delete props.msg
return props
}
getLogSeverity (level) {
if (level === 10 || level === 20) { return appInsights.Contracts.SeverityLevel.Verbose }
if (level === 40) { return appInsights.Contracts.SeverityLevel.Warning }
if (level === 50) { return appInsights.Contracts.SeverityLevel.Error }
if (level === 60) { return appInsights.Contracts.SeverityLevel.Critical }
return appInsights.Contracts.SeverityLevel.Information // 30
}
getLogSeverityName (severity) {
if (severity === appInsights.Contracts.SeverityLevel.Verbose) { return 'Verbose' }
if (severity === appInsights.Contracts.SeverityLevel.Warning) { return 'Warning' }
if (severity === appInsights.Contracts.SeverityLevel.Error) { return 'Error' }
if (severity === appInsights.Contracts.SeverityLevel.Critical) { return 'Critical' }
return 'Information'
}
insertException (item) {
const exception = this.getLogException(item)
if (!exception) { return }
const telemetry = {
exception,
properties: this.getLogProperties(item)
}
this.insights.trackException(telemetry)
}
insertTrace (item) {
const telemetry = {
message: this.getLogMessage(item),
severity: this.getLogSeverity(item.level),
properties: this.getLogProperties(item)
}
this.insights.trackTrace(telemetry)
}
async insert (entities = []) {
const self = this
const data = Array.isArray(entities) ? entities : [entities]
if (data.length <= 0) { return }
try {
data.forEach((entity) => {
self.insertTrace(entity)
if (entity.level === 50) { self.insertException(entity) }
})
return
} catch (err) {
throw Error(err.message)
}
}
insertStream () {
const self = this
const writeStream = new stream.Writable({ objectMode: true, highWaterMark: 1 })
writeStream._write = function (chunk, encoding, callback) {
self.insert(chunk).then(() => { callback(null) }).catch(callback)
}
return writeStream
}
}
module.exports = { Client }