@shellicar/winston-azure-application-insights 6.0.3 → 6.0.5

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
@@ -1,15 +1,31 @@
1
1
  # @shellicar/winston-azure-application-insights
2
2
 
3
- An [Azure Application Insights](https://azure.microsoft.com/en-us/services/application-insights/) transport for [Winston](https://github.com/winstonjs/winston) logging library
3
+ > An [Azure Application Insights](https://azure.microsoft.com/en-us/services/application-insights/) transport for [Winston](https://github.com/winstonjs/winston) logging library.
4
+
5
+ [![npm package](https://img.shields.io/npm/v/@shellicar/winston-azure-application-insights.svg)](https://npmjs.com/package/@shellicar/winston-azure-application-insights)
6
+ [![build status](https://github.com/shellicar/ecosystem/actions/workflows/node.js.yml/badge.svg)](https://github.com/shellicar/ecosystem/actions/workflows/node.js.yml)
7
+ [![AI Assisted](https://img.shields.io/badge/AI--Assisted-GitHub_Copilot-412991?logo=github)][copilot]
8
+
9
+ *Tests and documentation developed with assistance from [GitHub Copilot][copilot].*
10
+
11
+ > **Upgrading from v5.x?** See the [Migration Guide](#migration) for step-by-step upgrade instructions.
12
+
13
+ ## Features
14
+
15
+ - 🔄 **Dual SDK Support** - Works with both Application Insights v2 and v3 SDKs
16
+ - 🚀 **Simple Factory Functions** - Easy setup with `createApplicationInsightsTransport()` and `createWinstonLogger()`
17
+ - 🔍 **Automatic Error Detection** - Extracts Error objects from logs and sends them as Application Insights exceptions
18
+ - 📊 **Trace + Exception Logging** - Sends logs as traces while also tracking errors as detailed exceptions
19
+ - 🎯 **Flexible Filtering** - Optional trace and exception filters for fine-grained control
20
+ - 🔧 **Custom Severity Mapping** - Map Winston levels to Application Insights severity levels
21
+ - 🏠 **Local Development** - Log to console locally while sending to Application Insights in production
4
22
 
5
23
  ## Installation & Quick Start
6
24
 
7
25
  ```sh
8
- npm install @shellicar/winston-azure-application-insights
26
+ pnpm add @shellicar/winston-azure-application-insights
9
27
  ```
10
28
 
11
- ## Quick Example
12
-
13
29
  ```typescript
14
30
  import { createWinstonLogger, ApplicationInsightsVersion } from '@shellicar/winston-azure-application-insights';
15
31
  import applicationinsights from 'applicationinsights';
@@ -22,11 +38,248 @@ const logger = createWinstonLogger({
22
38
  client: applicationinsights.defaultClient
23
39
  },
24
40
  });
25
-
26
41
  logger.info('Hello World');
27
- logger.error('Something went wrong', new Error('Database connection failed'));
28
42
  ```
29
43
 
30
- ## Documentation
44
+ For more advanced usage and configuration, see the [examples](./examples) directory.
45
+
46
+ ## Motivation
47
+
48
+ When logging directly to Application Insights using the telemetry client, it makes debugging locally more difficult. Logging to console pollutes logs in Azure, so this provides a compromise.
49
+
50
+ I forked the original library to add support for Application Insights v3, which is relatively recent. I have also refactored it to handle certain error logging scenarios that weren't working as expected.
51
+
52
+ ## Feature Examples
53
+
54
+ - **Factory Functions** - Simple setup with clean API.
55
+
56
+ ```typescript
57
+ import applicationinsights from 'applicationinsights';
58
+ import { createApplicationInsightsTransport, ApplicationInsightsVersion } from '@shellicar/winston-azure-application-insights';
59
+
60
+ applicationinsights.setup().start();
61
+
62
+ const transport = createApplicationInsightsTransport({
63
+ version: ApplicationInsightsVersion.V3,
64
+ client: applicationinsights.defaultClient,
65
+ });
66
+ ```
67
+
68
+ - **Complete Logger Setup** - Create a Winston logger with both console and Application Insights.
69
+
70
+ ```typescript
71
+ import { createWinstonLogger, ApplicationInsightsVersion } from '@shellicar/winston-azure-application-insights';
72
+ import applicationinsights from 'applicationinsights';
73
+
74
+ const logger = createWinstonLogger({
75
+ winston: {
76
+ console: {
77
+ enabled: true,
78
+ format: {
79
+ output: 'json',
80
+ timestamp: true,
81
+ errors: true,
82
+ colorize: true,
83
+ },
84
+ },
85
+ defaults: {
86
+ level: 'info',
87
+ },
88
+ },
89
+ insights: {
90
+ version: ApplicationInsightsVersion.V3,
91
+ client: applicationinsights.defaultClient,
92
+ },
93
+ });
94
+
95
+ logger.info('Application started');
96
+ ```
97
+
98
+ - **Error Extraction** - Automatically detects Error objects and sends them as exceptions.
99
+
100
+ ```typescript
101
+ // Creates trace only
102
+ logger.error('Something went wrong');
103
+
104
+ // Creates EXCEPTION ONLY (no trace) - when first parameter is Error
105
+ logger.error(new Error('Database error'));
106
+
107
+ // Creates trace + exception (Error extracted from additional parameters)
108
+ logger.error('Operation failed', new Error('Timeout'));
109
+
110
+ // Creates trace + two exceptions (multiple Error objects)
111
+ logger.error('Multiple failures', new Error('DB error'), new Error('Cache error'));
112
+ ```
113
+
114
+ **Key Behaviour:** When you log an Error as the first parameter (`logger.error(new Error())`), it sends **only the exception** to Application Insights, not a trace. This avoids duplicate telemetry.
115
+
116
+ - **Properties Extraction** - Winston splat parameters become telemetry properties.
117
+
118
+ ```typescript
119
+ // Simple properties
120
+ logger.info('User logged in', { userId: 123, action: 'login' });
121
+
122
+ // Mixed types - Error objects are extracted, others become properties
123
+ logger.error('Complex operation failed', { userId: 123, operation: 'checkout' }, new Error('Payment failed'));
124
+ ```
125
+
126
+ - **Severity Mapping** - Winston levels map to Application Insights severity with priority fallback.
127
+
128
+ ```typescript
129
+ logger.error('Critical issue'); // → Error
130
+ logger.warn('Warning message'); // → Warning
131
+ logger.info('Info message'); // → Information
132
+ logger.verbose('Debug info'); // → Verbose
133
+
134
+ // Custom levels fall back to next available mapping
135
+ logger.log('audit', 'Audit event'); // → Falls back based on level priority
136
+ ```
137
+
138
+ - **Custom Severity Mapping** - Override default level mappings.
139
+
140
+ ```typescript
141
+ const transport = createApplicationInsightsTransport({
142
+ version: ApplicationInsightsVersion.V3,
143
+ client: defaultClient,
144
+ severityMapping: {
145
+ error: TelemetrySeverity.Error,
146
+ warn: TelemetrySeverity.Warning,
147
+ info: TelemetrySeverity.Information,
148
+ debug: TelemetrySeverity.Verbose,
149
+ // Custom levels
150
+ audit: TelemetrySeverity.Critical,
151
+ security: TelemetrySeverity.Error,
152
+ },
153
+ });
154
+ ```
155
+
156
+ - **Dual SDK Support** - Works with both Application Insights v2 and v3.
157
+
158
+ ```typescript
159
+ // Application Insights v2
160
+ import applicationinsights from 'applicationinsights'; // v2
161
+ const transport = createApplicationInsightsTransport({
162
+ version: ApplicationInsightsVersion.V2,
163
+ client: applicationinsights.defaultClient,
164
+ });
165
+
166
+ // Application Insights v3
167
+ import applicationinsights from 'applicationinsights'; // v3
168
+ const transport = createApplicationInsightsTransport({
169
+ version: ApplicationInsightsVersion.V3,
170
+ client: applicationinsights.defaultClient,
171
+ });
172
+ ```
173
+
174
+ - **Filtering** - Optional filters for traces and exceptions.
175
+
176
+ ```typescript
177
+ const transport = createApplicationInsightsTransport({
178
+ version: ApplicationInsightsVersion.V3,
179
+ client: defaultClient,
180
+ traceFilter: (trace) => trace.severity !== KnownSeverityLevel.Verbose,
181
+ exceptionFilter: (exception) => !exception.exception.message.includes('ignore'),
182
+ });
183
+ ```
184
+
185
+ - **Disable Exception Tracking** - Customise error detection logic.
186
+
187
+ ```typescript
188
+ const transport = createApplicationInsightsTransport({
189
+ version: 3,
190
+ client: defaultClient,
191
+ // Custom function to determine what counts as an error
192
+ isError: (obj) => obj instanceof CustomError,
193
+ });
194
+ ```
195
+
196
+ <!-- BEGIN_ECOSYSTEM -->
197
+
198
+ ## @shellicar TypeScript Ecosystem
199
+
200
+ ### Core Libraries
201
+
202
+ - [`@shellicar/core-config`](https://github.com/shellicar/core-config) - A library for securely handling sensitive configuration values like connection strings, URLs, and secrets.
203
+ - [`@shellicar/core-di`](https://github.com/shellicar/core-di) - A basic dependency injection library.
204
+
205
+ ### Reference Architectures
206
+
207
+ - [`@shellicar/reference-foundation`](https://github.com/shellicar/reference-foundation) - A comprehensive starter repository. Illustrates individual concepts.
208
+ - [`@shellicar/reference-enterprise`](https://github.com/shellicar/reference-enterprise) - A comprehensive starter repository. Can be used as the basis for creating a new Azure application workload.
209
+
210
+ ### Build Tools
211
+
212
+ - [`@shellicar/build-clean`](https://github.com/shellicar/build-clean) - Build plugin that automatically cleans unused files from output directories.
213
+ - [`@shellicar/build-version`](https://github.com/shellicar/build-version) - Build plugin that calculates and exposes version information through a virtual module import.
214
+ - [`@shellicar/build-graphql`](https://github.com/shellicar/build-graphql) - Build plugin that loads GraphQL files and makes them available through a virtual module import.
215
+
216
+ ### Framework Adapters
217
+
218
+ - [`@shellicar/svelte-adapter-azure-functions`](https://github.com/shellicar/svelte-adapter-azure-functions) - A [SvelteKit adapter](https://kit.svelte.dev/docs/adapters) that builds your app into an Azure Function.
219
+ - [`@shellicar/cosmos-query-builder`](https://github.com/shellicar/cosmos-query-builder) - Helper class for type safe advanced queries for Cosmos DB (Sql Core).
220
+
221
+ ### Logging & Monitoring
222
+
223
+ - [`@shellicar/winston-azure-application-insights`](https://github.com/shellicar/ecosystem/tree/main/packages/winston-azure-application-insights) - An [Azure Application Insights](https://azure.microsoft.com/en-us/services/application-insights/) transport for [Winston](https://github.com/winstonjs/winston) logging library.
224
+ - [`@shellicar/pino-applicationinsights-transport`](https://github.com/shellicar/pino-applicationinsights-transport) - [Azure Application Insights](https://azure.microsoft.com/en-us/services/application-insights) transport for [pino](https://github.com/pinojs/pino)
225
+
226
+ <!-- END_ECOSYSTEM -->
227
+
228
+ ## Configuration Options
229
+
230
+ - **version**: `ApplicationInsightsVersion.V2` or `ApplicationInsightsVersion.V3` - Application Insights SDK version (required)
231
+ - **client**: Application Insights client instance (required)
232
+ - **telemetryHandler**: Custom telemetry handler function (instead of version and client)
233
+ - **isError**: Custom function to determine what counts as an error (default: detects Error instances)
234
+ - **severityMapping**: Custom Winston level to Application Insights severity mapping
235
+ - **traceFilter**: Optional function to filter traces before sending
236
+ - **exceptionFilter**: Optional function to filter exceptions before sending
237
+
238
+ ### Troubleshooting
239
+
240
+ #### Missing Connection String
241
+
242
+ ```txt
243
+ No instrumentation key or connection string was provided
244
+ ```
245
+
246
+ Set the connection string via environment variable or setup parameter. See the [Application Insights setup guide](https://github.com/microsoft/ApplicationInsights-node.js?tab=readme-ov-file#get-started) for detailed instructions.
247
+
248
+ #### Duplicate API Registration
249
+
250
+ ```txt
251
+ Attempted duplicate registration of API: context
252
+ ```
253
+
254
+ Your environment already loaded Application Insights. Use the existing client without calling setup():
255
+
256
+ ```typescript
257
+ import applicationinsights from 'applicationinsights';
258
+ const transport = createApplicationInsightsTransport({
259
+ version: ApplicationInsightsVersion.V3,
260
+ client: applicationinsights.defaultClient,
261
+ });
262
+ ```
263
+
264
+ #### Multiple/Duplicate Traces
265
+
266
+ Application Insights auto-collects from console and Winston. Disable auto-collection:
267
+
268
+ ```typescript
269
+ setup().setAutoCollectConsole(false).start();
270
+ ```
271
+
272
+ ## Migration
273
+
274
+ ### Upgrading from v5.x to v6.x
275
+
276
+ v6.x includes significant improvements to error handling, type safety, and configuration structure. See the complete [Migration Guide](./MIGRATION.md) for detailed upgrade instructions.
277
+
278
+ ## Credits & Inspiration
279
+
280
+ - [willmorgan/winston-azure-application-insights](https://github.com/willmorgan/winston-azure-application-insights) - Forked from willmorgan's version
281
+ - [bragma/winston-azure-application-insights](https://github.com/bragma/winston-azure-application-insights) - Original library by bragma
282
+ - [Winston](https://github.com/winstonjs/winston) - Universal logging library for Node.js
283
+ - [Azure Application Insights](https://azure.microsoft.com/en-us/services/application-insights/) - Application Performance Management service
31
284
 
32
- For full documentation, visit the [GitHub repository](https://github.com/shellicar/winston-azure-application-insights).
285
+ [copilot]: https://github.com/features/copilot