New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

cf-nodejs-logging-support

Package Overview
Dependencies
Maintainers
4
Versions
100
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cf-nodejs-logging-support - npm Package Compare versions

Comparing version 4.0.0 to 5.0.0

.eslintrc.json

179

cf-nodejs-logging-support-core/log-core.js

@@ -1,5 +0,5 @@

var util = require('util');
var os = require('os');
var uuid = require('uuid/v4');
var jwt = require('jsonwebtoken');
var util = require("util");
var os = require("os");
var uuid = require("uuid/v4");
var jwt = require("jsonwebtoken");

@@ -13,15 +13,25 @@ const envDynLogHeader = "DYN_LOG_HEADER";

const nsPerSec = 1e9;
const logType = "log";
const loggingLevels = {
'error': 0,
'warn': 1,
'info': 2,
'verbose': 3,
'debug': 4,
'silly': 5
"error": 0,
"warn": 1,
"info": 2,
"verbose": 3,
"debug": 4,
"silly": 5
};
var logLevelInt = 2;
var convinientLogFunctions = [];
for (var key in loggingLevels) {
convinientLogFunctions[key] = function (bKey) {
return function () {
var args = [bKey, ...arguments];
logMessage.apply(this, args);
}
}(key);
}
var fixedValues = {};
var initDummy = "{}";
var logLevelInt = 2;
var pattern = null;

@@ -36,2 +46,3 @@ var stdout = process.stdout;

var dynLogLevelHeader = dynLogLevelDefaultHeader;
var dynLogLevelKey = null;

@@ -48,9 +59,9 @@ // Initializes the core logger, including setup of environment var defined settings

// Read dyn log level key from environemt var.
// Read dyn log level key from environment var.
dynLogLevelKey = process.env[envDynLogKey];
}
};
var setConfig = function (config) {
precompileConfig(config);
}
};

@@ -95,11 +106,11 @@ var precompileConfig = function (config) {

initDummy = JSON.stringify(logObject);
}
};
var getPreLogConfig = function () {
return preLogConfig;
}
};
var getPostLogConfig = function () {
return postLogConfig;
}
};

@@ -114,3 +125,3 @@ var handleConfigDefaults = function (configEntry, logObject, fallbacks) {

}
}
};

@@ -131,3 +142,3 @@ // Replace all fields, which are marked to be reduced and do not equal to their default value, empty or "-", to reductedPlaceholder.

}
}
};

@@ -137,4 +148,4 @@ // Stringify and log given object to console. If a custom pattern is set, the referenced object fields are used to replace the references.

var output = "";
if (null != pattern) {
if (undefined !== logObject && logObject != null) {
if (pattern != null) {
if (logObject !== undefined && logObject != null) {
output = "";

@@ -144,3 +155,3 @@ var rest = pattern.split(patternDivider);

//iterates over split custom pattern, where n%3=0 is text outside the marked fields and n%3=2 are the fields to be replaced (inside {{}}), n elem rest.
for (i = 0; i < (rest.length - 1) / 3; i++) {
for (var i = 0; i < (rest.length - 1) / 3; i++) {
output += rest[i * 3];

@@ -160,7 +171,7 @@ value = logObject[rest[2 + i * 3]];

} else {
output = (undefined !== logObject && validObject(logObject)) ? JSON.stringify(logObject) : '';
output = (logObject !== undefined && validObject(logObject)) ? JSON.stringify(logObject) : "";
}
stdout.write(output + os.EOL);
}
};

@@ -173,4 +184,5 @@ // Sets the minimum logging level. Messages with a lower level will not be forwarded. (Levels: error, warn, info, verbose, debug, silly)

}
return false
}
return false;
};
// Gets the minimum logging level. (Levels: error, warn, info, verbose, debug, silly)

@@ -200,4 +212,2 @@ var getLoggingLevel = function () {

var obj = {};
var fallbacks = [];

@@ -226,8 +236,8 @@ var selfReferences = [];

for (var key in fallbacks) {
obj[key] = fallbacks[key](obj);
for (var kFallback in fallbacks) {
obj[kFallback] = fallbacks[kFallback](obj);
}
for (var key in selfReferences) {
obj[key] = obj[selfReferences[key]];
for (var kSelfReference in selfReferences) {
obj[kSelfReference] = obj[selfReferences[kSelfReference]];
}

@@ -250,5 +260,5 @@

// if root is a string => parse it to an object. Otherwise => use it directly as object.
if (typeof root === 'string') {
if (typeof root === "string") {
rootObj = JSON.parse(root);
} else if (typeof root === 'object') {
} else if (typeof root === "object") {
rootObj = root;

@@ -272,3 +282,3 @@ } else {

return value;
}
};

@@ -284,3 +294,3 @@ var checkLoggingLevel = function (level, dynamicLogLevel) {

return (threshold >= loggingLevels[level]);
}
};

@@ -315,9 +325,9 @@ // Writes the given log file to stdout

var dynamicLogLevel = this.dynamicLogLevel;
var logObject;
var level = args[0];
var level = args[0];
if (!checkLoggingLevel(level, this.dynamicLogLevel)) {
return false;
} else {
var logObject = initLog();
logObject = initLog();
logObject.level = level;

@@ -330,3 +340,3 @@ }

if (typeof args[args.length - 1] === 'object') {
if (typeof args[args.length - 1] === "object") {
if (validObject(args[args.length - 1])) {

@@ -353,8 +363,8 @@ customFields = args[args.length - 1];

if (customFields != null) {
logObject.custom_fields = customFields.constructor == Array ? [] : {};
logObject.custom_fields = {};
for (var key in customFields) {
if (!((typeof customFields[key]) == "string")) {
if ((typeof customFields[key]) == "string") {
logObject.custom_fields[key] = customFields[key];
} else {
logObject.custom_fields[key] = JSON.stringify(customFields[key]);
} else {
logObject.custom_fields[key] = customFields[key];
}

@@ -389,13 +399,47 @@ }

return false;
}
};
var bindLogFunctions = function (req) {
req.logMessage = logMessage;
req.getCorrelationId = getCorrelationId;
req.setCorrelationId = setCorrelationId;
var bindLogFunctions = function (logObj) {
logObj.logMessage = logMessage;
logObj.getCorrelationId = getCorrelationId;
logObj.setCorrelationId = setCorrelationId;
logObj.setDynamicLoggingLevel = setDynamicLoggingLevel;
};
var bindLogFunctionsToReq = function (req) {
req.getCorrelationObject = getCorrelationObject;
req.setDynamicLoggingLevel = setDynamicLoggingLevel;
bindLogFunctions(req);
generateLogger(req);
}
var generateLogger = function (req) {
req.logger = {};
req.logger.logObject = req.logObject;
bindLogFunctions(req.logger);
bindConvenienceMethods(req.logger);
}
var bindLogFunctionsToCorrelationObj = function (logObj) {
bindConvenienceMethods(logObj);
bindLogFunctions(logObj);
}
var bindConvenienceMethods = function (logObj) {
for (var key in convinientLogFunctions) {
logObj[key] = convinientLogFunctions[key];
}
}
var getCorrelationObject = function () {
if (this.logObject != null && this.logger != null) {
return this.logger;
} else {
var newContext = {};
newContext.logObject = {};
newContext.logObject.correlation_id = uuid();
bindLogFunctionsToCorrelationObj(newContext);
return newContext;
}
};
var validObject = function (obj) {

@@ -412,15 +456,2 @@ if (obj === null || obj === undefined) {

var getCorrelationObject = function () {
var context = this;
var newContext = {};
newContext.logObject = {};
if (context.logObject != null) {
newContext.logObject.correlation_id = context.logObject.correlation_id;
} else {
newContext.logObject.correlation_id = uuid();
}
bindLogFunctions(newContext);
return newContext;
}
// Sets the dynamic log level for the request to the given level

@@ -430,3 +461,3 @@ var setDynamicLoggingLevel = function (levelName) {

context.dynamicLogLevel = getLogLevelFromName(levelName);
}
};

@@ -437,3 +468,3 @@ var writeStaticFields = function (logObject) {

}
}
};

@@ -444,3 +475,3 @@ // overrides Values in ALL Network logs (will impact log parsing, so use with caution!), returns true if field is set.

if (value == undefined || value == null) {
fixedValues[field] = null;
fixedValues[field] = undefined;
return true;

@@ -453,3 +484,3 @@ } else {

return false;
}
};

@@ -459,3 +490,3 @@ // Get the name of the dynamic log level header

return dynLogLevelHeader;
}
};

@@ -466,3 +497,3 @@ // Gets the log level number from a given level name

return (loggingLevels[levelName.toLowerCase()] != undefined) ? loggingLevels[levelName.toLowerCase()] : null;
}
};

@@ -477,5 +508,4 @@ // Binds the Loglevel extracted from JWT token to the given req

}
};
}
// Verifies the given JWT and returns its payload.

@@ -495,3 +525,3 @@ var verifyAndDecodeJWT = function (token, key) {

}
}
};

@@ -511,3 +541,3 @@

exports.setLogPattern = setLogPattern;
exports.bindLogFunctions = bindLogFunctions;
exports.bindLogFunctionsToReq = bindLogFunctionsToReq;
exports.getCorrelationObject = getCorrelationObject;

@@ -519,2 +549,3 @@ exports.setConfig = setConfig;

exports.getDynLogLevelHeaderName = getDynLogLevelHeaderName;
exports.bindDynLogLevel = bindDynLogLevel;
exports.bindDynLogLevel = bindDynLogLevel;
exports.bindConvenienceMethods = bindConvenienceMethods;
// Log network activity for express applications
var uuid = require("uuid/v4");
var core;
var fixedValues = [];

@@ -13,3 +10,3 @@ var setCoreLogger = function (coreLogger) {

core.setConfig(config);
}
};

@@ -84,8 +81,8 @@ // Set the minimum logging level. Messages with a lower level, will not be forwarded. (Levels: error, warn, info, verbose, debug, silly)

for (var key in fallbacks) {
logObject[key] = fallbacks[key](req, res, logObject);
for (var kFallback in fallbacks) {
logObject[kFallback] = fallbacks[kFallback](req, res, logObject);
}
for (var key in selfReferences) {
logObject[key] = logObject[selfReferences[key]];
for (var kSelfReference in selfReferences) {
logObject[kSelfReference] = logObject[selfReferences[kSelfReference]];
}

@@ -97,9 +94,9 @@

req.logObject = logObject;
core.bindLogFunctions(req);
core.bindLogFunctionsToReq(req);
res.on('finish', function () {
res.on("finish", function () {
finishLog();
});
res.on('header', function () {
res.on("header", function () {
finishLog();

@@ -139,8 +136,8 @@ });

for (var key in fallbacks) {
logObject[key] = fallbacks[key](req, res, logObject);
for (var kFallback in fallbacks) {
logObject[kFallback] = fallbacks[kFallback](req, res, logObject);
}
for (var key in selfReferences) {
logObject[key] = logObject[selfReferences[key]];
for (var kSelfReference in selfReferences) {
logObject[kSelfReference] = logObject[selfReferences[kSelfReference]];
}

@@ -174,7 +171,7 @@

return core.getCorrelationObject();
}
};
var overrideField = function (field, value) {
return core.overrideField(field, value);
}
};

@@ -181,0 +178,0 @@ exports.overrideField = overrideField;

// Log network activity for express applications
var uuid = require("uuid/v4");
var core;
var fixedValues = [];

@@ -13,3 +11,3 @@ var setCoreLogger = function (coreLogger) {

core.setConfig(config);
}
};

@@ -69,8 +67,8 @@ // Set the minimum logging level. Messages with a lower level, will not be forwarded. (Levels: error, warn, info, verbose, debug, silly)

for (var key in fallbacks) {
logObject[key] = fallbacks[key](req, res, logObject);
for (var kFallback in fallbacks) {
logObject[kFallback] = fallbacks[kFallback](req, res, logObject);
}
for (var key in selfReferences) {
logObject[key] = logObject[selfReferences[key]];
for (var kSelfReference in selfReferences) {
logObject[kSelfReference] = logObject[selfReferences[kSelfReference]];
}

@@ -84,11 +82,9 @@

core.bindLogFunctions(req);
core.bindLogFunctionsToReq(req);
var start = Date.now();
res.on('finish', function () {
res.on("finish", function () {
finishLog();
});
res.on('header', function () {
res.on("header", function () {
finishLog();

@@ -127,8 +123,8 @@ });

for (var key in fallbacks) {
logObject[key] = fallbacks[key](req, res, logObject);
for (var kFallback in fallbacks) {
logObject[kFallback] = fallbacks[kFallback](req, res, logObject);
}
for (var key in selfReferences) {
logObject[key] = logObject[selfReferences[key]];
for (var kSelfReference in selfReferences) {
logObject[kSelfReference] = logObject[selfReferences[kSelfReference]];
}

@@ -162,7 +158,7 @@ //override values with predefined values

return core.getCorrelationObject();
}
};
var overrideField = function (field, value) {
return core.overrideField(field, value);
}
};

@@ -169,0 +165,0 @@ exports.overrideField = overrideField;

// Log network activity for restify applications
var uuid = require("uuid/v4");
var core;
var fixedValues = [];

@@ -13,3 +11,3 @@ var setCoreLogger = function (coreLogger) {

core.setConfig(config);
}
};

@@ -23,4 +21,2 @@ // Set the minimum logging level. Messages with a lower level, will not be forwarded. (Levels: error, warn, info, verbose, debug, silly)

var logNetwork = function (req, res, next) {
var logSent = false;
var logObject = core.initLog();

@@ -80,8 +76,8 @@

for (var key in fallbacks) {
logObject[key] = fallbacks[key](req, res, logObject);
for (var kFallback in fallbacks) {
logObject[kFallback] = fallbacks[kFallback](req, res, logObject);
}
for (var key in selfReferences) {
logObject[key] = logObject[selfReferences[key]];
for (var kSelfReference in selfReferences) {
logObject[kSelfReference] = logObject[selfReferences[kSelfReference]];
}

@@ -95,5 +91,5 @@

core.bindLogFunctions(req);
core.bindLogFunctionsToReq(req);
res.on('finish', function () {
res.on("finish", function () {

@@ -128,8 +124,8 @@

for (var key in fallbacks) {
logObject[key] = fallbacks[key](req, res, logObject);
for (var kFallback in fallbacks) {
logObject[kFallback] = fallbacks[kFallback](req, res, logObject);
}
for (var key in selfReferences) {
logObject[key] = logObject[selfReferences[key]];
for (var kSelfReference in selfReferences) {
logObject[kSelfReference] = logObject[selfReferences[kSelfReference]];
}

@@ -151,3 +147,3 @@

// Logs message and custom fields
var logMessage = function (args) {
var logMessage = function () {
core.logMessage.apply(this, arguments);

@@ -163,7 +159,7 @@ };

return core.getCorrelationObject();
}
};
var overrideField = function (field, value) {
return core.overrideField(field, value);
}
};

@@ -170,0 +166,0 @@ exports.overrideField = overrideField;

@@ -1,3 +0,3 @@

const Transport = require('winston-transport');
const { SPLAT } = require('triple-beam');
const Transport = require("winston-transport");
const { SPLAT } = require("triple-beam");

@@ -7,4 +7,4 @@ const CfNodejsLoggingSupportLogger = class CfNodejsLoggingSupportLogger extends Transport {

super(options);
this.name = 'CfNodejsLoggingSupportLogger';
this.level = options.level || 'info';
this.name = "CfNodejsLoggingSupportLogger";
this.level = options.level || "info";
this.logMessage = options.logMessage;

@@ -14,3 +14,3 @@ }

log(info) {
if (!!info[SPLAT]) {
if (info[SPLAT]) {
this.logMessage.apply(this, [info.level, info.message, ...info[SPLAT]]);

@@ -21,6 +21,6 @@ } else {

}
}
};
exports.createTransport = function (options) {
return new CfNodejsLoggingSupportLogger(options);
}
};

@@ -198,5 +198,6 @@ var uuid = require("uuid/v4");

source: {
type: "static",
value: "-"
}
type: "header",
name: "remote-user"
},
default: "-"
}, {

@@ -214,7 +215,9 @@ name: "direction",

source: {
type: "special"
type: "header",
name: "x-forwarded-for"
},
fallback: (req, res, logObj) => {
default: ""
/*fallback: (req, res, logObj) => {
return req.headers['x-forwarded-for'] == null ? "" : req.headers['x-forwarded-for'];
}
}*/
}, {

@@ -221,0 +224,0 @@ name: "remote_ip",

@@ -42,2 +42,4 @@ //loading core logger functionality

coreLogger.bindConvenienceMethods(exports);
exports.createWinstonTransport = function (options) {

@@ -44,0 +46,0 @@ if (!options) {

{
"name": "cf-nodejs-logging-support",
"version": "4.0.0",
"version": "5.0.0",
"description": "Logging tool for Cloud Foundry",

@@ -29,3 +29,8 @@ "keywords": [

"codecov": "^3.1.0",
"eslint": "^5.12.1",
"eslint": "^5.13.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"import-fresh": "^2.0.0",

@@ -32,0 +37,0 @@ "istanbul": "^0.4.4",

@@ -12,3 +12,3 @@ # Node.js Logging Support for Cloud Foundry

#### Version 2.0 introduced logging without Winston and changed custom fields to be parsed and reported as strings regardless of original type.
#### Version 3.0 introduced dynamic log levels, sensitive data reduction and a redesigned field configuration system
#### Version 3.0 introduced dynamic log level thresholds, sensitive data reduction and a redesigned field configuration system
#### Version 4.0 changed winston transport api

@@ -21,3 +21,3 @@

* Logging levels
* Dynamic logging level (per request)
* Dynamic logging level threshold (per request)
* Extendable field configuration

@@ -49,3 +49,3 @@ * Sensitive data reduction

// Context bound custom message
req.logMessage("info", "Hello World will be sent");
req.logger.info("Hello World will be sent");

@@ -57,3 +57,3 @@ res.send('Hello World');

// Formatted log message free of request context
log.logMessage("info", "Server is listening on port %d", 3000);
log.info("Server is listening on port %d", 3000);
```

@@ -90,3 +90,3 @@

// Context bound custom message
req.logMessage("info", "request bound information:", {
req.logger.info("request bound information:", {
"some": "info"

@@ -98,3 +98,3 @@ });

// Formatted log message free of request context
log.logMessage("info", "Server is listening on port %d", 3000);
log.info("Server is listening on port %d", 3000);
```

@@ -141,2 +141,20 @@

### Convenience Methods
Instead of using logMessage(...), you could also use:
| Standard | Convenient |
|------------------------------------------------|-----------------------------------|
| ```log.logMessage("info",...)``` | ```log.info(...)``` |
| ```req.logMessage("info",...)``` | ```req.logger.info(...)``` |
| ```correlationObject.logMessage("info",...)``` | ```correlationObject.info(...)``` |
The convenience methods are currently only available for the common node.js logging levels:
- error
- warn
- info
- verbose
- debug
- silly
### Sensitive data redaction

@@ -155,14 +173,15 @@ Version 3.0.0 and above implements a sensitive data redaction system, which deactivates the logging of sensitive fields. The field will contain 'redacted' instead of the original content.

This behavior matches with the corresponding mechanism in the [CF Java Logging Support](https://github.com/SAP/cf-java-logging-support/wiki/Overview#logging-sensitive-user-data) library.
### Dynamic log levels
Sometimes it is useful to change the logging level for a specific request. This can be achieved by dynamic log levels set by a special header field or directly inside the corresponding request handler.
### Dynamic logging level threshold
Sometimes it is useful to change the logging level threshold for a specific request. This can be achieved using a special header field or setting directly within the corresponding request handler. Changing the logging level threshold only affects the presence of logs but not their individual logging levels.
#### Change log level via header field
You can change the log level for a specific request by providing a JSON Web Token ([JWT](https://de.wikipedia.org/wiki/JSON_Web_Token)) via the request header. This way it is not necessary to redeploy your app for every log level change.
#### Change logging level threshold via header field
You can change the logging level threshold for a specific request by providing a JSON Web Token ([JWT](https://de.wikipedia.org/wiki/JSON_Web_Token)) via the request header. This way it is not necessary to redeploy your app for every logging level change.
##### 1 Creating a JWT
JWTs are signed claims, which consists of a header, a payload and a signature. You can create JWTs by using the [TokenCreator](https://github.com/SAP/cf-nodejs-logging-support/tree/master/tools/token-creator) from the tools folder.
JWTs are signed claims, which consist of a header, a payload and a signature. You can create JWTs by using the [TokenCreator](https://github.com/SAP/cf-nodejs-logging-support/tree/master/tools/token-creator) from the tools folder.
Basically, JWTs are signed with RSA or HMAC signing algorithms. But we decided to support RDA algorithms (RS256, RS384 and RS512) only. In contrast to HMAC algorithms (HS256, HS384 and HS512), RSA algorithms are asymmetric and therefore require key pairs (public and private key).
Basically, JWTs are signed using RSA or HMAC signing algorithms. But we decided to support RSA algorithms (RS256, RS384 and RS512) only. In contrast to HMAC algorithms (HS256, HS384 and HS512), RSA algorithms are asymmetric and therefore require key pairs (public and private key).

@@ -190,7 +209,7 @@ The tool mentioned above takes a log level, creates a key pair and signs the resulting JWT with the private key. The payload of a JWT looks like this:

##### 3 Attaching JWTs to requests
Provide the created JWTs via a header field named 'SAP-LOG-LEVEL'. The logging level will be set to the provided level for the request (and also corresponding custom log messages).
Provide the created JWTs via a header field named 'SAP-LOG-LEVEL'. The logging level threshold will be set to the provided level for the request (and also corresponding custom log messages).
Note: If the provided JWT cannot be verified, is expired or contains an invalid logging level, the library ignores it and uses the global logging level.
Note: If the provided JWT cannot be verified, is expired or contains an invalid logging level, the library ignores it and uses the global logging level threshold.
If you want to use another header name for the JWT, you can specify it via an enviroment variable:
If you want to use another header name for the JWT, you can specify it using an enviroment variable:
```

@@ -200,3 +219,3 @@ DYN_LOG_HEADER: MY-HEADER-FIELD

#### Change log level within request handler
#### Change logging level threshold within request handlers
You can also change the log level for all requests of a specific request handler by calling:

@@ -279,3 +298,9 @@ ```js

```
This will replace the value of the previously empty msg field for network logs with YOUR_CUSTOM_MSG.
This will replace the value of the previously not existing msg field for network logs with YOUR_CUSTOM_MSG.
If the overridden field is already existing, it will be overridden by YOUR_CUSTOM_MSG for ALL subsequent network logs, until you
remove the override with:
```js
log.overrideNetworkField("msg", null);
```
If you use this override feature in conjunction with a log parser, make sure you will not violate any parsing rules.

@@ -282,0 +307,0 @@

@@ -7,3 +7,3 @@ var program = require('commander');

"error", "warn", "info", "verbose", "debug", "silly"
]
];

@@ -50,3 +50,3 @@ const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/g;

// Nice to have: KeyPair generation
console.log("Error: Generating keypairs on-the-fly is currently not supported by this script. Please provide a private key by using the --key or --keyfile option.")
console.log("Error: Generating keypairs on-the-fly is currently not supported by this script. Please provide a private key by using the --key or --keyfile option.");
return;

@@ -53,0 +53,0 @@ }

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc