How to use simple node logger module - node.js

This below function created mylogfile but can't error the logs of api response with timestamp and error in app
const SimpleNodeLogger = require('simple-node-logger'),
opts = {
logFilePath:'mylogfile.log',
timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
},
log = SimpleNodeLogger.createSimpleLogger( opts );

seems you're missing something ... here's an example
// utilities/logger.js
const SimpleNodeLogger = require('simple-node-logger');
const opts = {
logFilePath:'mylogfile.log',
timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
};
const log = SimpleNodeLogger.createSimpleLogger(opts);
module.exports = log;
and then, just use it
// index.js
const logger = require('./utilities/logger');
logger.info(`I'm an information line`);
logger.debug(`I'm a debug line`);
logger.error(`I'm an error line`);
that will output in a new created file called mylogfile.log:
2020-12-25 13:37:17.139 INFO I'm an information line
2020-12-25 13:37:17.140 ERROR I'm an error line
set the log level if you want to output more info, like debug. All options are in the package page titled "How to use"

Related

Datadog APM Resource column is not giving correct values

I am facing trouble where datadog RESOURCE column is not giving the correct value as shown in the image. Really need some help here.
My assumption is that, it is happening because http tags are not appearing correctly. I think datadog itself add the http tags and it's value.
The http.path_group & http.route should have this value "/api-pim2/v1/attribute/search" but for some reason it's not coming correctly.
I am using this library dd-trace at backend. The tracers options which i provided are these
{"logInjection":true,"logLevel":"debug","runtimeMetrics":true,"analytics":true,"debug":true,"startupLogs":true,"tags":{"env":"dev02","region":"us-east-1","service":"fabric-gateway-pim-ecs"}}
The initialising code looks like this which ran at the start of my app
app/lib/tracer.js:
const config = require('config')
const tracerOptions = config.get('dataDog.tracer.options')
const logger = require('app/lib/logger')
const tracer = require('dd-trace').init({
...tracerOptions,
enabled: true,
logger
})
module.exports = tracer
I also tried to set the http.path_group & http.route tag manually but still it's not updating the values. Though i can add the new tags like http.test which has the same value which i was trying to override in http.path_group & http.route
const addTagsToRootSpan = tags => {
const span = tracer.scope().active()
if (span) {
const root = span.context()._trace.started[0]
for (const tag of tags) {
root.setTag(tag.key, tag.value)
}
log.debug('Tags added')
} else {
log.debug('Trace span could not be found')
}
}
...
const tags = [
{ key: 'http.path_group', value: request.originalUrl },
{ key: 'http.route', value: request.originalUrl },
{ key: 'http.test', value: request.originalUrl }
addTagsToRootSpan(tags)
...
I was requiring tracer.js file at the start of my app where server was listening.
require('app/lib/tracer')
app.listen(port, err => {
if (err) {
log.error(err)
return err
}
log.info(`Your server is ready for ${config.get('stage')} on PORT ${port}!`)
})
By enabling the debug option in datadog tracer init function. I can see the tracer logs and what values are passed by the library for http.route and resource.
I was confused by this line according to the data dog tracers doc you should init first before importing any instrumented module.
// This line must come before importing any instrumented module.
const tracer = require('dd-trace').init();
But for me http.route & resource value get correct if i initialise it on my routing file. They start giving me complete route "/api-pim2/v1/attribute/search" instead of only "/api-pim2"
routes/index.js:
const router = require('express').Router()
require('app/lib/tracer')
const attributeRouter = require('app/routes/v1/attribute')
router.use('/v1/attribute', attributeRouter)
module.exports = router
I am not accepting this answer yet because i am still confused where to initialise the tracer. Maybe someone can explain better. I am just writing this answer if someone else facing the issue can try this. Might just resolve their problem.

How to share config folder between main app and library module?

This is my plan to setup myNodeApp, which has these folders:
config, src, node_modules/#myCompany/logging
in the library #myCompany/logging, i have code like this,
myWinston.js
const { createLogger } = require('winston');
const logger = createLogger({
level: config.get('logging').level, // this config is the one from myNodeApp
prettyPrint: true』);
module.exports = logger;
myLogger.js
const logger = require(./myWinston');
const warning = (myWarningMsg) => {
logger.warn(myWarningMsg);
}
module.exports = { warning };
Now in the main app code,
myApp.js
const { logger } = require('#myCompany/logging');
...
logger.warning('my warning msg here');
...
The problem is myWinston.js within the library #myCompany/logging, it needs a logging level from the main app.
What's the best way to pass this info from myNodeApp/config pls ?
Another idea see if it can work,
#myCompany/logging this lib has a config folder, can be used for testing within this lib.
When install #myCompany/logging for the myNodeApp, i can exclude config folder by using .npmignore. So logging will use the config folder from myNodeApp.
Comments pls ?
I think it is possible this way:
logger from npm modules can export constructor function:
// file in node_modules/#myCompany/logging/index.js
const { createLogger } = require('winston');
module.exports = exports = function(loggerConfig){
return createLogger({
level: loggerConfig.level,
prettyPrint: loggerConfig.prettyPring
});
};
and it can be used this way in index.js file, so config is provided properly
const config = require('./lib/config'); // all top level app config is loaded from some file in your project
config.logger.appName = 'web'; // you can customize global config here, for example, you have 2 components - web server and background process, and appName can depict it
const logger = require('#myCompany/logging')(config.logger); //here you instantiate logger with global config loaded
logger.info('Web application is preparing to start!');
//lot of code here

Generating a json for a icon cheatsheet

I'm trying to generate a json file containing the filenames of all the files in a certain directory. I need this to create a cheatsheet for icons.
Currently I'm trying to run a script locally via terminal, to generate the json. That json will be the input for a react component that will display icons. That component works, the create json script doesn't.
Code for generating the json
const fs = require('fs');
const path = require('path');
/**
* Create JSON file
*/
const CreateJson = () => {
const files = [];
const dir = '../icons';
fs.readdirSync(dir).forEach(filename => {
const name = path.parse(filename);
const filepath = path.resolve(dir, filename);
const stat = fs.statSync(filepath);
const isFile = stat.isFile();
if (isFile) files.push({ name });
});
const data = JSON.stringify(files, null, 2);
fs.writeFileSync('../Icons.json', data);
};
module.exports = CreateJson;
I run it in terminal using
"create:json": "NODE_ENV=build node ./scripts/CreateJson.js"
I expect a json file to be created/overridden. But terminal returns:
$ NODE_ENV=build node ./scripts/CreateJson.js
✨ Done in 0.16s.
Any pointers?
You are creating a function CreateJson and exporting it, but you are actually never calling it.
You can get rid of the module.exports and replace it with CreateJson().
When you'll execute the file with node, it will see the function declaration, and a call to it, whereas with your current code there is no call.

Electron app - logging to file in production

I want to get logs if something wrong happens to my electron app when in production mode i.e after giving .exe file to a user wrt windows platform.
How to go about it, how can i basically write my errors to a file which will be in cyclic in nature.
Take a look at electron log
// Setup file logging
const log = require('electron-log');
log.transports.file.level = 'info';
log.transports.file.file = __dirname + 'log.log';
// Log a message
log.info('log message');
EDIT:
As mentioned in the comments the "log.transports.file.file" is deprecated.
Instead I would suggest to use the following method.
log.transports.file.resolvePath = () => __dirname + "/log.log";
Create a file next to you electron.js called logger.js
const path = require("path");
const log = require('electron-log');
log.transports.file.resolvePath = () => path.join(__dirname, '/logsmain.log');
log.transports.file.level = "info";
exports.log = (entry) => log.info(entry)
then on your app
const logger = require('electron').remote.require('./logger');
logger.log("some text")
Please have a look here:
https://www.electronjs.org/docs/api/net-log
const { netLog } = require('electron')
app.whenReady().then(async () => {
await netLog.startLogging('/path/to/net-log')
// After some network events
const path = await netLog.stopLogging()
console.log('Net-logs written to', path)
})

exporting console.log from a module in node.js

I'm using a customized version of node-clim, but I want to put away all the customization code in a module of its own and require() it in my main app. But I can't seem to do that..
This code works
var util = require('util');
var clim = require('clim')
clim.logWrite = function(level, prefixes, msg) {
...
customizing code
...
process.stderr.write(...);
};
var console = clim();
console.log('hey'); // works
But in trying to put the above in a separate file clim.js and exporting the console object...
module.export = console;
and require()ing it in my main app doesn't work..
var console = require('./clim');
console.log('hey');
// ^ TypeError: Object #<Object> has no method 'log'
What am I doing wrong?
Change
module.export = console;
to
module.exports = console;

Resources