Adding Winston logging to a React JS application - javascript

I want to implement Winston logging on my React application (made using create-react-app).
I have installed Winston:
npm install winston
I import it into the application app.js:
import winston from 'winston';
Then attempt to implement a logger:
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
Then:
logger.info('Hello from ReactJS');
However, when I then go to run the application I get 20+ errors in the browser:
All suggesting that various modules cannot be found. If I then comment out the logger it loads fine with no errors.
Am I doing this wrong?

Related

Vue add i18n returns ERROR TypeError: Cannot read property 'minVersion' of undefined

I try to run vue cli vue add i18n to generate localisation using i18n to my local. It got error
Done in 37.95s.
✔ Successfully installed plugin: vue-cli-plugin-i18n
ERROR TypeError: Cannot read property 'minVersion' of undefined
TypeError: Cannot read property 'minVersion' of undefined
at module.exports.pkg (/mnt/disks/data_disks/teja/localised/forexsignals/node_modules/vue-cli-plugin-i18n/prompts.js:5:26)
at invoke (/usr/local/lib/node_modules/#vue/cli/lib/invoke.js:74:25)
at process._tickCallback (internal/process/next_tick.js:68:7)
The i18n.js and other files aren't generated.
Otherwise, I want to try to add i18n manually using npm install then add the files manually, but stuck at editing vue.config.js, here below my vue.config.js shown
var PrerenderSpaPlugin = require('prerender-spa-plugin')
var path = require('path')
var Renderer = PrerenderSpaPlugin.PuppeteerRenderer;
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV !== 'production') return
return {
plugins: [
new PrerenderSpaPlugin(
{
staticDir: path.resolve(__dirname, 'dist'),
routes: ['/', '/join-free-channel'],
renderer: new Renderer({
headless: true
})
}
),
]
}
}
}
I have installed prerendering for my vue app that updates my vue.config.js file, but still have no idea about how to add internationalisation to the app by editing vue.config.js
I recently had this problem, this is caused by the absence of the #vue/cli-shared-utils dependency. I'm not sure why it was not installed when installing vue-cli.
A quick solution to this problem is to install this dependency: npm i #vue/cli-shared-utils
After installing, run vue add i18n again and it should work fine.
I faced a similar problem. I saw this error after vue add i18n, but I think they are the same
TypeError: Cannot read property 'split' of undefined
So, I just removed the package-lock.json file and then executed vue add i18n again.
It worked for me.

Vue js babel build error after installing prerender-spa-plugin

So I have a vue-js application and today I started using prerender-spa-plugin to generate some static pages for better SEO. When I run npm run build, everything works perfect, no errors. Now when I want to run the development server with npm run serve, I get the following error (only a part of it)
error in ./src/main.js
Module build failed (from ./node_modules/babel-
loader/lib/index.js):
Error: .plugins[0] must include an object
at assertPluginItem (/Users/user/Desktop/app/node_modules/#babel/core/lib/config/validation/option-assertions.js:231:13)
So I guess the problem has to do with the babel plugin loader. So I commended every part of my code using prerender-spa-plugin, but I still get the same error. I hope someone can point me to the right direction.
My babel.config.js
const removeConsolePlugin = []
if(process.env.NODE_ENV === 'production') {
removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
presets: [
'#vue/app'
],
plugins: [removeConsolePlugin]
}
My vue.config.js
const path = require('path');
const PrerenderSpaPlugin = require('prerender-spa-plugin');
const productionPlugins = [
new PrerenderSpaPlugin({
staticDir: path.join(__dirname, 'dist'),
routes: ['/', '/documentation'],
renderer: new PrerenderSpaPlugin.PuppeteerRenderer({
// We need to inject a value so we're able to
// detect if the page is currently pre-rendered.
inject: {},
// Our view component is rendered after the API
// request has fetched all the necessary data,
// so we create a snapshot of the page after the
// `data-view` attribute exists in the DOM.
//renderAfterElementExists: '[data-view]',
}),
}),
];
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
config.plugins.push(...productionPlugins);
}
}
}

Can Winston Logger be used on the front-end for logging?

I am creating full mean stack app with
NodeJs , Angular 6 , ExpressJs and MongoDB
I have managed to create a server and its working perfectly, instead of using console.log when logging errors in my app I have decided to use Winston Logger here is what I have now
Server side
var appRoot = require('app-root-path');
var winston = require('winston');
// define the custom settings for each transport (file, console)
var options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
const logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console)
],
exitOnError: false, // do not exit on handled exceptions
});
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write: function (message, encoding) {
// use the 'info' log level so the output will be picked up by both transports (file and console)
logger.info(message);
},
};
module.exports = logger;
Note: Winston in server side works perfectly
Client-Side
I want to use winston in my client side angular 6 app .
Example: in one of my components i have this.
import * as logger from "winston";
.........
this.activeRouter.params.subscribe((params) => {
// tslint:disable-next-line:prefer-const
let id = params['id'];
this.moviesService.getReview(id)
.subscribe(review => {
console.log(review);
this.review = review;
});
});
As you can see I am using console.log(review) , Instead of console log I would like to use Winston .
How to use Winston logger in client-side ? am newbie to all this stuff any help will be apreciated.
Yeah it is possible, however default transport for browser is very limited. I recommend to use https://www.npmjs.com/package/winston-transport-browserconsole
npm install winston-transport-browserconsole -S
It is easy to use and supports logging json objects:
import * as winston from "winston";
import BrowserConsole from 'winston-transport-browserconsole';
const level = "debug";
winston.configure({
transports: [
new BrowserConsole(
{
format: winston.format.simple(),
level,
},
),
],
});
winston.debug("DEBUG ", {a: 1, b: "two"});
Yes - it can (technically) be used in the browser. Should it be? Almost definitely not (sadly). Winston is a fantastic logger for node. But, emphasis on "for node". If you want to use it on the client, you would need to add a bunch of node polyfills in addition to winston itself, which is very large relative to other client loggers. Between winston and those polyfills you are going to significantly increase the size of your artifact. Also, just fyi webpack 5 removed those node polyfills, so you would need to add them back manually.
According to this ticket: https://github.com/winstonjs/winston/issues/287 it's almost ready for browser use? Or mostly ready? It sounds like they recently started supporting logging in a browser environment.

Winston js. My log files aren't rotating after exceeding maxsize

I have the following winston configuration:
'use strict'
import winston from 'winston'
import config from '../../config/environment'
export default winston.createLogger({
level: 'info',
format: winston.format.printf(info => info.message),
transports: [
new winston.transports.Console(),
new winston.transports.File({
filename: `${config.logsPath}/express.error.log`,
maxsize: 300,
level: 'error'
}),
new winston.transports.File({
filename: `${config.logsPath}/express.log`,
maxsize: 300
})]
})
None of this files are rotating after they reach the 300 bytes threshold.
You are using the version 3.0.0 release candidate which has a bug in its File transport. Basically, once over the maxsize threshold, internal self.filename variable was not being updated so _createStream would re-open the append stream to the existing file and continue writing to it. It works the first time around because self.filename is set when initializing from options.
I've submitted a PR which fixes the issue. Alternatively, you can revert to 2.4.0 where this isn't an issue.

Winston logger not being printed on new line

This is my winston logger -
var winston = require('winston')
var logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
// log which takes care of all the MAS scoring - node clusters and servers
filename: './test.log',
level: 'info',
json: true,
eol: 'rn'
})
]
})
And when I run the actual logger:
logger.info('hi', 'it meeeeee')
logger.info('hi', 'it youuuuuu')
It prints out like this in the test.log file -
{"level":"info","message":"hi it meeeeee","timestamp":"2016-08-18T08:42:01.768Z"}rn{"level":"info","message":"hi it youuuuuu","timestamp":"2016-08-18T08:42:01.770Z"}rn
And I want it to be like this:
{"level":"info","message":"hi it meeeeee","timestamp":"2016-08-18T08:42:01.768Z"}
{"level":"info","message":"hi it youuuuuu","timestamp":"2016-08-18T08:42:01.770Z"}
How is this possible? I have read this question Node.js winston logger; How to start from a newline when insert log into log file? - however it does not solve the issue in my case.
I.e. if I open in Notepad ++, command line or Sublime text I still get the same issue.
Try this eol: \r\n
Look official documentation

Categories