@apolitical/logger 1.0.1 → 2.0.0-beta.2

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/CHANGELOG.md CHANGED
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+
9
+ ## [2.0.0] - 2022-01-18
10
+ ### Changed
11
+ - Dependencies
12
+ - Node version
13
+ - Labels definition instead of metadata
14
+ ### Added
15
+ - Logger middleware
16
+
17
+ ## [1.0.2] - 2021-07-08
18
+ ### Updated
19
+ - Dependencies
20
+
8
21
  ## [1.0.1] - 2021-04-23
9
22
  ### Added
10
23
  - Cloud function support
package/README.md CHANGED
@@ -41,14 +41,15 @@ const childLogger = logger.where(__filename, 'debugging');
41
41
  childLogger.debug('Accessed:', { count: 0 });
42
42
  ```
43
43
 
44
- ### The _metadata_ object
44
+ ### The _labels_ object
45
45
 
46
- And also, the metadata object allows you to keep extra info along the logger journey:
46
+ And also, the labels allow you to keep extra info along the logger journey:
47
47
 
48
48
  ```
49
49
  const opts = {
50
- metadata: {
51
- serviceName: 'apolitical-service'
50
+ labels: {
51
+ name: 'apolitical-service',
52
+ version: 'v1.0.0'
52
53
  }
53
54
  };
54
55
  const logger = apoliticalLogger(opts);
package/package.json CHANGED
@@ -1,26 +1,22 @@
1
1
  {
2
2
  "name": "@apolitical/logger",
3
- "version": "1.0.1",
3
+ "version": "2.0.0-beta.2",
4
4
  "description": "Node.js module to expose Apolitical's logger service",
5
5
  "author": "Apolitical Group Limited <engineering@apolitical.co>",
6
- "contributors": [
7
- "Anouska Hopkins <anouska.hopkins@apolitical.co>",
8
- "Antonio Cordasco <antonio.cordasco@apolitical.co>",
9
- "Dorothy Yau <dorothy.yau@apolitical.co>",
10
- "Laura Hanna-White <laura.hanna-white@apolitical.co>",
11
- "Fatimat Gbajabiamila <fatimat.gbajabiamila@apolitical.co>",
12
- "Renzo Rozza <renzo.rozza@apolitical.co>",
13
- "Rihards Jukna <rihards.jukna@apolitical.co>"
14
- ],
15
6
  "license": "MIT",
16
- "main": "index.js",
7
+ "main": "src/index.js",
8
+ "files": [
9
+ "src"
10
+ ],
17
11
  "scripts": {
18
12
  "test": "jest --bail --runInBand",
19
13
  "integration-test": "jest --bail --runInBand",
20
14
  "unit-test": "jest --bail --runInBand",
21
15
  "lint": "eslint --ext .js ./src",
22
16
  "format": "prettier --write 'src/**/*.+(js|json)'",
23
- "audit": "audit-ci -h"
17
+ "lint-format": "lint-staged",
18
+ "audit": "audit-ci -h",
19
+ "prepare": "husky install"
24
20
  },
25
21
  "keywords": [
26
22
  "Backend",
@@ -28,31 +24,53 @@
28
24
  "Node Modules"
29
25
  ],
30
26
  "dependencies": {
31
- "@google-cloud/logging-winston": "4.0.4",
32
- "awilix": "4.3.3",
33
- "winston": "3.3.3"
27
+ "@google-cloud/logging-winston": "4.1.1",
28
+ "awilix": "6.0.0",
29
+ "winston": "3.4.0"
34
30
  },
35
31
  "devDependencies": {
36
- "audit-ci": "3.2.0",
37
- "eslint": "7.24.0",
38
- "eslint-config-prettier": "8.2.0",
39
- "eslint-plugin-jest": "24.3.5",
40
- "eslint-plugin-prettier": "3.4.0",
41
- "husky": "4.3.8",
42
- "jest": "26.6.3",
43
- "lint-staged": "10.5.4",
44
- "prettier": "2.2.1"
32
+ "@apolitical/eslint-config": "1.0.0-beta.0",
33
+ "audit-ci": "5.1.2",
34
+ "husky": "7.0.4",
35
+ "jest": "27.4.7",
36
+ "jest-junit": "13.0.0",
37
+ "lint-staged": "12.1.7"
45
38
  },
46
39
  "engines": {
47
- "node": ">=12.20.1"
40
+ "node": ">=16.13.2"
41
+ },
42
+ "eslintConfig": {
43
+ "extends": "@apolitical/eslint-config/base.config"
48
44
  },
49
- "husky": {
50
- "hooks": {
51
- "pre-commit": "lint-staged && yarn test"
52
- }
45
+ "prettier": "@apolitical/eslint-config/prettier.config",
46
+ "jest": {
47
+ "bail": true,
48
+ "clearMocks": true,
49
+ "collectCoverage": true,
50
+ "collectCoverageFrom": [
51
+ "src/**/*.js"
52
+ ],
53
+ "coverageDirectory": "coverage",
54
+ "coveragePathIgnorePatterns": [
55
+ "/node_modules/"
56
+ ],
57
+ "coverageReporters": [
58
+ "text",
59
+ "lcov"
60
+ ],
61
+ "resetMocks": true,
62
+ "testEnvironment": "node",
63
+ "testTimeout": 60000,
64
+ "maxConcurrency": 1,
65
+ "maxWorkers": 1,
66
+ "reporters": [
67
+ "default",
68
+ "jest-junit"
69
+ ],
70
+ "testResultsProcessor": "jest-junit"
53
71
  },
54
72
  "lint-staged": {
55
- "*.js": "eslint --cache --fix",
56
- "*.+(js|json)": "prettier --write"
73
+ "*.js": "eslint --cache --fix --ignore-path .gitignore",
74
+ "*.+(js|json)": "prettier --write --ignore-path .gitignore"
57
75
  }
58
76
  }
package/src/config.js CHANGED
@@ -9,7 +9,7 @@ module.exports = {
9
9
  },
10
10
  LOGGER: {
11
11
  LOGGING_LEVELS: ['error', 'warn', 'info', 'debug'],
12
- ALLOWED_METADATA: ['serviceName', 'requestId'],
12
+ ALLOWED_LABELS: ['name', 'version'],
13
13
  TRANSPORTS: {
14
14
  FILE: {
15
15
  ERROR_OPTIONS: {
package/src/container.js CHANGED
@@ -2,28 +2,22 @@
2
2
 
3
3
  // External Modules
4
4
  const { createContainer, asValue, asFunction } = require('awilix');
5
-
6
5
  const path = require('path');
7
6
  const winston = require('winston');
8
7
  const winstonGoogle = require('@google-cloud/logging-winston');
9
-
10
8
  // Configuration
11
9
  const config = require('./config');
12
-
13
10
  // Services
14
11
  const loggerService = require('./services/logger.service');
15
12
 
16
13
  const container = createContainer();
17
14
  container.register({
18
15
  // External Modules
19
-
20
16
  path: asValue(path),
21
17
  winston: asValue(winston),
22
18
  winstonGoogle: asValue(winstonGoogle),
23
-
24
19
  // Configuration
25
20
  config: asValue(config),
26
-
27
21
  // Services
28
22
  loggerService: asFunction(loggerService).singleton(),
29
23
  });
package/src/index.js ADDED
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ const { resolve } = require('./container');
4
+
5
+ const winstonGoogle = resolve('winstonGoogle');
6
+ const loggerService = resolve('loggerService');
7
+
8
+ module.exports = {
9
+ createLogger: loggerService,
10
+ loggerMiddleware: winstonGoogle.express.makeMiddleware,
11
+ };
@@ -1,79 +1,89 @@
1
1
  'use strict';
2
2
 
3
- module.exports = ({ path, winston, winstonGoogle, config }) => ({ logLevel = 'info', metadata = {} }) => {
4
- const { LOGGING_LEVELS, ALLOWED_METADATA } = config.LOGGER;
5
- const { ERROR_OPTIONS, COMBINED_OPTIONS } = config.LOGGER.TRANSPORTS.FILE;
6
- const { CLOUD_FUNCTION, CREDENTIALS } = config.GOOGLE;
3
+ module.exports =
4
+ ({ path, winston, winstonGoogle, config }) =>
5
+ ({ logLevel = 'info', labels = {} }) => {
6
+ const { LOGGING_LEVELS, ALLOWED_LABELS } = config.LOGGER;
7
+ const { ERROR_OPTIONS, COMBINED_OPTIONS } = config.LOGGER.TRANSPORTS.FILE;
8
+ const { CLOUD_FUNCTION, CREDENTIALS } = config.GOOGLE;
7
9
 
8
- function allowedMetadata() {
9
- return ALLOWED_METADATA.reduce((acc, cv) => {
10
- if (metadata[cv]) {
11
- acc[cv] = metadata[cv];
12
- }
13
- return acc;
14
- }, {});
15
- }
10
+ function allowedLabels() {
11
+ return ALLOWED_LABELS.reduce((acc, cv) => {
12
+ if (labels[cv]) {
13
+ acc[cv] = labels[cv];
14
+ }
15
+ return acc;
16
+ }, {});
17
+ }
16
18
 
17
- function loggingLevels() {
18
- return LOGGING_LEVELS.reduce((acc, cv, idx) => {
19
- acc[cv] = idx;
20
- return acc;
21
- }, {});
22
- }
19
+ function loggingLevels() {
20
+ return LOGGING_LEVELS.reduce((acc, cv, idx) => {
21
+ acc[cv] = idx;
22
+ return acc;
23
+ }, {});
24
+ }
23
25
 
24
- function loggerTransports() {
25
- const transports = [];
26
- if (config.NODE_ENV === 'production') {
27
- if (CLOUD_FUNCTION || CREDENTIALS) {
28
- transports.push(new winstonGoogle.LoggingWinston());
26
+ function loggerTransports() {
27
+ const transports = [];
28
+ if (config.NODE_ENV === 'production') {
29
+ if (CLOUD_FUNCTION || CREDENTIALS) {
30
+ transports.push(
31
+ new winstonGoogle.LoggingWinston({
32
+ labels,
33
+ serviceContext: {
34
+ service: labels.name,
35
+ version: labels.version,
36
+ },
37
+ }),
38
+ );
39
+ } else {
40
+ transports.push(new winston.transports.Console());
41
+ }
29
42
  } else {
30
43
  transports.push(new winston.transports.Console());
44
+ transports.push(new winston.transports.File(ERROR_OPTIONS));
45
+ transports.push(new winston.transports.File(COMBINED_OPTIONS));
31
46
  }
32
- } else {
33
- transports.push(new winston.transports.Console());
34
- transports.push(new winston.transports.File(ERROR_OPTIONS));
35
- transports.push(new winston.transports.File(COMBINED_OPTIONS));
47
+ return transports;
36
48
  }
37
- return transports;
38
- }
39
-
40
- function loggerFormat() {
41
- return winston.format.combine(winston.format.colorize(), winston.format.simple());
42
- }
43
49
 
44
- function filterFunctionality(logger) {
45
- return LOGGING_LEVELS.reduce(
46
- (acc, cv) => {
47
- acc[cv] = (message, extras = null) => {
48
- if (extras) logger[cv](message, extras);
49
- else logger[cv](message);
50
- };
51
- return acc;
52
- },
53
- { metadata: logger.defaultMeta },
54
- );
55
- }
50
+ function loggerFormat() {
51
+ return winston.format.combine(winston.format.colorize(), winston.format.simple());
52
+ }
56
53
 
57
- function createWrapper(logger) {
58
- function where(filePath, method) {
59
- const file = path.basename(filePath);
60
- const childLogger = logger.child({ location: { file, method } });
61
- return createWrapper(childLogger);
54
+ function filterFunctionality(logger) {
55
+ return LOGGING_LEVELS.reduce(
56
+ (acc, cv) => {
57
+ acc[cv] = (message, extras = null) => {
58
+ if (extras) logger[cv](message, extras);
59
+ else logger[cv](message);
60
+ };
61
+ return acc;
62
+ },
63
+ { labels: logger.labels, transports: logger.transports },
64
+ );
62
65
  }
63
- function write(message) {
64
- logger.info(message);
66
+
67
+ function createWrapper(logger) {
68
+ function where(filePath, method) {
69
+ const file = path.basename(filePath);
70
+ const childLogger = logger.child({ labels: { file, method } });
71
+ return createWrapper(childLogger);
72
+ }
73
+ function write(message) {
74
+ logger.info(message);
75
+ }
76
+ const instance = filterFunctionality(logger);
77
+ return Object.assign(instance, { where, stream: { write } });
65
78
  }
66
- const instance = filterFunctionality(logger);
67
- return Object.assign(instance, { where, stream: { write } });
68
- }
69
79
 
70
- const loggerInstance = winston.createLogger({
71
- level: logLevel,
72
- levels: loggingLevels(),
73
- format: loggerFormat(),
74
- defaultMeta: allowedMetadata(),
75
- transports: loggerTransports(),
76
- });
80
+ const loggerInstance = winston.createLogger({
81
+ labels: allowedLabels(),
82
+ level: logLevel,
83
+ levels: loggingLevels(),
84
+ format: loggerFormat(),
85
+ transports: loggerTransports(),
86
+ });
77
87
 
78
- return createWrapper(loggerInstance);
79
- };
88
+ return createWrapper(loggerInstance);
89
+ };
package/.eslintrc DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "extends": [
3
- "eslint:recommended",
4
- "plugin:prettier/recommended",
5
- "plugin:jest/recommended"
6
- ],
7
- "env": {
8
- "node": true,
9
- "es6": true,
10
- "jest": true
11
- },
12
- "parserOptions": {
13
- "ecmaVersion": 2018
14
- },
15
- "plugins": ["jest"]
16
- }
package/.gitlab-ci.yml DELETED
@@ -1,22 +0,0 @@
1
- # External jobs
2
- include:
3
- - project: 'apolitical/templates/gitlab-pipelines'
4
- ref: master
5
- file: 'Node-Testing.gitlab-ci.yml'
6
-
7
- stages:
8
- - cache
9
- - test
10
- - publish
11
-
12
- publish-module:
13
- stage: publish
14
- image: node:12.20.1-alpine3.11
15
- extends:
16
- - .use-cache
17
- only:
18
- - tags
19
- - /^v\d+\.\d+\.\d+$/
20
- script:
21
- - echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > ~/.npmrc
22
- - yarn publish --access=public
package/.prettierrc DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "useTabs": false,
3
- "printWidth": 120,
4
- "tabWidth": 2,
5
- "singleQuote": true,
6
- "trailingComma": "all"
7
- }
package/index.js DELETED
@@ -1,5 +0,0 @@
1
- 'use strict';
2
-
3
- const container = require('./src/container');
4
-
5
- module.exports = container.resolve('loggerService');
package/jest.config.js DELETED
@@ -1,188 +0,0 @@
1
- // For a detailed explanation regarding each configuration property, visit:
2
- // https://jestjs.io/docs/en/configuration.html
3
-
4
- module.exports = {
5
- // All imported modules in your tests should be mocked automatically
6
- // automock: false,
7
-
8
- // Stop running tests after the first failure
9
- // bail: false,
10
-
11
- // Respect "browser" field in package.json when resolving modules
12
- // browser: false,
13
-
14
- // The directory where Jest should store its cached dependency information
15
- // cacheDirectory: "/var/folders/w1/bgm1c1j969lf2mfml3w9hf400000gn/T/jest_dx",
16
-
17
- // Automatically clear mock calls and instances between every test
18
- clearMocks: true,
19
-
20
- // Indicates whether the coverage information should be collected while executing the test
21
- collectCoverage: true,
22
-
23
- // An array of glob patterns indicating a set of files for which coverage
24
- // information should be collected
25
- collectCoverageFrom: ['src/**/{!(container),}.js'],
26
-
27
- // The directory where Jest should output its coverage files
28
- coverageDirectory: 'coverage',
29
-
30
- // An array of regexp pattern strings used to skip coverage collection
31
- coveragePathIgnorePatterns: ['/node_modules/'],
32
-
33
- // A list of reporter names that Jest uses when writing coverage reports
34
- coverageReporters: ['text', 'lcov'],
35
-
36
- // An object that configures minimum threshold enforcement for coverage results
37
- // coverageThreshold: null,
38
-
39
- // Make calling deprecated APIs throw helpful error messages
40
- // errorOnDeprecated: false,
41
-
42
- // Force coverage collection from ignored files usin a array of glob patterns
43
- // forceCoverageMatch: [],
44
-
45
- // Force Jest to exit after all tests have completed running.
46
- // This is useful when resources set up by test code cannot be adequately cleaned up
47
- // forceExit: true,
48
-
49
- // A path to a module which exports an async function that is triggered once
50
- // before all test suites
51
- // globalSetup: '<rootDir>/test/global-setup',
52
-
53
- // A path to a module which exports an async function that is triggered once after all test suites
54
- // globalTeardown: null,
55
-
56
- // A set of global variables that need to be available in all test environments
57
- // globals: {},
58
-
59
- // An array of directory names to be searched recursively up from the requiring module's location
60
- // moduleDirectories: [
61
- // "node_modules"
62
- // ],
63
-
64
- // An array of file extensions your modules use
65
- // moduleFileExtensions: [
66
- // "js",
67
- // "json",
68
- // "jsx",
69
- // "node"
70
- // ],
71
-
72
- // A map from regular expressions to module names that allow to stub out
73
- // resources with a single module
74
- // moduleNameMapper: {},
75
-
76
- // An array of regexp pattern strings, matched against all module paths
77
- // before considered 'visible' to the module loader
78
- // modulePathIgnorePatterns: [],
79
-
80
- // Activates notifications for test results
81
- // notify: false,
82
-
83
- // An enum that specifies notification mode. Requires { notify: true }
84
- // notifyMode: "always",
85
-
86
- // A preset that is used as a base for Jest's configuration
87
- // preset: null,
88
-
89
- // Run tests from one or more projects
90
- // projects: null,
91
-
92
- // Use this configuration option to add custom reporters to Jest
93
- // reporters: undefined,
94
-
95
- // Automatically reset mock state between every test
96
- resetMocks: true,
97
-
98
- // Reset the module registry before running each individual test
99
- // resetModules: false,
100
-
101
- // A path to a custom resolver
102
- // resolver: null,
103
-
104
- // Automatically restore mock state between every test
105
- // restoreMocks: false,
106
-
107
- // The root directory that Jest should scan for tests and modules within
108
- // rootDir: null,
109
-
110
- // A list of paths to directories that Jest should use to search for files in
111
- // roots: [
112
- // "<rootDir>"
113
- // ],
114
-
115
- // Allows you to use a custom runner instead of Jest's default test runner
116
- // runner: "jest-runner",
117
-
118
- // The paths to modules that run some code to configure or set up the
119
- // testing environment before each test
120
- // setupFiles: ['<rootDir>/node_modules/regenerator-runtime/runtime'],
121
-
122
- // The path to a module that runs some code to configure or set up the
123
- // testing framework before each test
124
- // setupTestFrameworkScriptFile: null,
125
-
126
- // A list of paths to snapshot serializer modules Jest should use for snapshot testing
127
- // snapshotSerializers: [],
128
-
129
- // The test environment that will be used for testing
130
- testEnvironment: 'node',
131
-
132
- // Options that will be passed to the testEnvironment
133
- // testEnvironmentOptions: {},
134
-
135
- // Adds a location field to test results
136
- // testLocationInResults: false,
137
-
138
- // The glob patterns Jest uses to detect test files
139
- // testMatch: [
140
- // "**/__tests__/**/*.js?(x)",
141
- // "**/?(*.)+(spec|test).js?(x)"
142
- // ],
143
-
144
- // An array of regexp pattern strings that are matched against all
145
- // test paths, matched tests are skipped
146
- // testPathIgnorePatterns: [
147
- // "/node_modules/"
148
- // ],
149
-
150
- // The regexp pattern Jest uses to detect test files
151
- // testRegex: "",
152
-
153
- // This option allows the use of a custom results processor
154
- // testResultsProcessor: null,
155
-
156
- // This option allows use of a custom test runner
157
- // testRunner: "jasmine2",
158
-
159
- // This option sets the URL for the jsdom environment. It is reflected in
160
- // properties such as location.href
161
- // testURL: "http://localhost",
162
-
163
- // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
164
- // timers: "real",
165
-
166
- // A map from regular expressions to paths to transformers
167
- // transform: null,
168
-
169
- // An array of regexp pattern strings that are matched against all source
170
- // file paths, matched files will skip transformation
171
- // transformIgnorePatterns: [
172
- // "/node_modules/"
173
- // ],
174
-
175
- // An array of regexp pattern strings that are matched against all modules
176
- // before the module loader will automatically return a mock for them
177
- // unmockedModulePathPatterns: undefined,
178
-
179
- // Indicates whether each individual test should be reported during the run
180
- // verbose: null,
181
-
182
- // An array of regexp patterns that are matched against all source file paths before
183
- // re-running tests in watch mode
184
- // watchPathIgnorePatterns: [],
185
-
186
- // Whether to use watchman for file crawling
187
- // watchman: true,
188
- };
@@ -1,27 +0,0 @@
1
- // Jest Snapshot v1, https://goo.gl/fbAQLP
2
-
3
- exports[`Logger Service Child should create child logger with where method 1`] = `
4
- Object {
5
- "debug": [Function],
6
- "error": [Function],
7
- "info": [Function],
8
- "metadata": Object {
9
- "requestId": "some-request-id",
10
- "serviceName": "some-service-name",
11
- },
12
- "stream": Object {
13
- "write": [Function],
14
- },
15
- "warn": [Function],
16
- "where": [Function],
17
- }
18
- `;
19
-
20
- exports[`Logger Service Child should create child using child method 1`] = `
21
- Object {
22
- "location": Object {
23
- "file": "logger.spec.js",
24
- "method": "test",
25
- },
26
- }
27
- `;
@@ -1,25 +0,0 @@
1
- 'use strict';
2
-
3
- const { createContainer, asValue, asFunction } = require('awilix');
4
-
5
- // External Modules
6
- const path = require('path');
7
-
8
- // Local Modules
9
- const config = require('../../../src/config');
10
- const loggerService = require('../../../src/services/logger.service');
11
-
12
- // Stubs
13
- const winston = require('./stubs/winston.stub');
14
- const winstonGoogle = require('./stubs/winston.google.stub');
15
-
16
- const testContainer = createContainer();
17
- testContainer.register({
18
- path: asValue(path),
19
- winston: asValue(winston),
20
- winstonGoogle: asValue(winstonGoogle),
21
- config: asValue(config),
22
- loggerService: asFunction(loggerService).singleton(),
23
- });
24
-
25
- module.exports = testContainer;
@@ -1,43 +0,0 @@
1
- 'use strict';
2
-
3
- const container = require('./container');
4
-
5
- const winston = container.resolve('winston');
6
- const config = container.resolve('config');
7
-
8
- const loggerOpts = {
9
- logLevel: 'info',
10
- metadata: {
11
- serviceName: 'some-service-name',
12
- requestId: 'some-request-id',
13
- },
14
- };
15
-
16
- const loggerStub = {
17
- defaultMeta: {
18
- serviceName: loggerOpts.metadata.serviceName,
19
- requestId: loggerOpts.metadata.requestId,
20
- },
21
- child: jest.fn(),
22
- };
23
-
24
- config.LOGGER.LOGGING_LEVELS.forEach((level) => {
25
- loggerStub[level] = jest.fn();
26
- });
27
-
28
- module.exports = {
29
- setUp() {
30
- loggerStub.child.mockReturnValue(loggerStub);
31
- winston.format.combine.mockReturnValue('colorize and simple');
32
- winston.format.colorize.mockReturnValue('colorize');
33
- winston.format.simple.mockReturnValue('simple');
34
- winston.createLogger.mockReturnValue(loggerStub);
35
-
36
- return {
37
- logger: {
38
- opts: loggerOpts,
39
- stub: loggerStub,
40
- },
41
- };
42
- },
43
- };
@@ -1,122 +0,0 @@
1
- 'use strict';
2
-
3
- const container = require('./container');
4
-
5
- const config = container.resolve('config');
6
- const winston = container.resolve('winston');
7
- const winstonGoogle = container.resolve('winstonGoogle');
8
- const loggerService = container.resolve('loggerService');
9
-
10
- const loggerHelper = require('./logger.helper');
11
-
12
- describe('Logger Service', () => {
13
- const { LOGGING_LEVELS } = config.LOGGER;
14
- let logger = null;
15
-
16
- beforeEach(() => {
17
- ({ logger } = loggerHelper.setUp());
18
- });
19
-
20
- describe('General', () => {
21
- test('should be exposed as function', () => {
22
- expect(typeof loggerService).toBe('function');
23
- });
24
-
25
- test('should provide logger levels', () => {
26
- const instance = loggerService(logger.opts);
27
- LOGGING_LEVELS.forEach((level) => {
28
- expect(typeof instance[level]).toBe('function');
29
- });
30
- });
31
-
32
- test('should invoke logger methods with message', () => {
33
- const instance = loggerService(logger.opts);
34
- LOGGING_LEVELS.forEach((level) => {
35
- instance[level]('some-message');
36
- expect(logger.stub[level]).toHaveBeenCalledTimes(1);
37
- expect(logger.stub[level]).toHaveBeenLastCalledWith('some-message');
38
- });
39
- });
40
-
41
- test('should invoke logger methods with extras', () => {
42
- const instance = loggerService(logger.opts);
43
- LOGGING_LEVELS.forEach((level) => {
44
- instance[level]('some-message', { bar: 'foo' });
45
- expect(logger.stub[level]).toHaveBeenCalledTimes(1);
46
- expect(logger.stub[level]).toHaveBeenLastCalledWith('some-message', {
47
- bar: 'foo',
48
- });
49
- });
50
- });
51
- });
52
-
53
- describe('Transport', () => {
54
- test('should use console and files in non-prod envs', () => {
55
- loggerService(logger.opts);
56
- const params = winston.createLogger.mock.calls[0][0];
57
- expect(params.transports.length).toEqual(3);
58
- expect(winston.transports.Console).toHaveBeenCalledTimes(1);
59
- expect(winston.transports.File).toHaveBeenCalledTimes(2);
60
- });
61
-
62
- test('should use console in prod env (without credentials)', () => {
63
- config.NODE_ENV = 'production';
64
- loggerService(logger.opts);
65
- const params = winston.createLogger.mock.calls[0][0];
66
- expect(params.transports.length).toEqual(1);
67
- expect(winston.transports.Console).toHaveBeenCalledTimes(1);
68
- });
69
-
70
- test('should use google winston in prod env (with credentials)', () => {
71
- config.NODE_ENV = 'production';
72
- config.GOOGLE.CREDENTIALS = 'some-credentials';
73
- loggerService(logger.opts);
74
- const params = winston.createLogger.mock.calls[0][0];
75
- expect(params.transports.length).toEqual(1);
76
- expect(winstonGoogle.LoggingWinston).toHaveBeenCalledTimes(1);
77
- });
78
-
79
- test('should use google winston in prod env (with cloud function)', () => {
80
- config.NODE_ENV = 'production';
81
- config.GOOGLE.GOOGLE_CLOUD_FUNCTION = 'true';
82
- loggerService(logger.opts);
83
- const params = winston.createLogger.mock.calls[0][0];
84
- expect(params.transports.length).toEqual(1);
85
- expect(winstonGoogle.LoggingWinston).toHaveBeenCalledTimes(1);
86
- });
87
- });
88
-
89
- describe('Metadata', () => {
90
- test('should not use default metadata', () => {
91
- loggerService({});
92
- const params = winston.createLogger.mock.calls[0][0];
93
- expect(params.defaultMeta).toEqual({});
94
- });
95
-
96
- test('should use default metadata', () => {
97
- loggerService(logger.opts);
98
- const params = winston.createLogger.mock.calls[0][0];
99
- expect(params.defaultMeta).toEqual({
100
- requestId: 'some-request-id',
101
- serviceName: 'some-service-name',
102
- });
103
- });
104
- });
105
-
106
- describe('Child', () => {
107
- test('should create child logger with where method', () => {
108
- const instance = loggerService(logger.opts);
109
- const childLogger = instance.where(__filename, 'test');
110
- expect(logger.stub.child).toHaveBeenCalledTimes(1);
111
- expect(childLogger).toMatchSnapshot();
112
- });
113
-
114
- test('should create child using child method', () => {
115
- const instance = loggerService(logger.opts);
116
- instance.where(__filename, 'test');
117
- expect(logger.stub.child).toHaveBeenCalledTimes(1);
118
- const params = logger.stub.child.mock.calls[0][0];
119
- expect(params).toMatchSnapshot();
120
- });
121
- });
122
- });
@@ -1,5 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = {
4
- LoggingWinston: jest.fn(),
5
- };
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = {
4
- format: {
5
- combine: jest.fn(),
6
- colorize: jest.fn(),
7
- simple: jest.fn(),
8
- },
9
- transports: {
10
- Console: jest.fn(),
11
- File: jest.fn(),
12
- },
13
- createLogger: jest.fn(),
14
- };