winston module not behaving properly - javascript

How can I update log file when using Winston to handle logging for node.js. Below is the code which I tried. Only first time the data is getting saved in log file.
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: '2012-07-09.log' })
]
});
logger.log('info', 'Test Log Message', { anything: 'This is metadata' });
Im using Node version 0.10.10 and winston 0.7.1
Any help on this will be really helpful. Thanks

Update to winston 7.2
https://github.com/mozilla/persona/commit/ecd695c52d9edbfa46b710ec8832c9fdf890ae16
I use 0.10.24 .It works for me now

Related

Node.js 'fs' throws an ENOENT error after adding auto-generated Swagger server code

Preamble
To start off, I'm not a developer; I'm just an analyst / product owner with time on their hands. While my team's actual developers have been busy finishing off projects before year-end I've been attempting to put together a very basic API server in Node.js for something we will look at next year.
I used Swagger to build an API spec and then used the Swagger code generator to get a basic Node.js server. The full code is near the bottom of this question.
The Problem
I'm coming across an issue when writing out to a log file using the fs module. I know that the ENOENT error is usually down to just specifying a path incorrectly, but the behaviour doesn't occur when I comment out the Swagger portion of the automatically generated code. (I took the logging code directly out of another tool I built in Node.js, so I'm fairly confident in that portion at least...)
When executing npm start, a few debugging items write to the console:
"Node Server Starting......
Current Directory:/mnt/c/Users/USER/Repositories/PROJECT/api
Trying to log data now!
Mock mode: disabled
PostgreSQL Pool created successfully
Your server is listening on port 3100 (http://localhost:3100)
Swagger-ui is available on http://localhost:3100/docs"
but then fs throws an ENOENT error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '../logs/logEvents2021-12-24.log'
Emitted 'error' event at:
at lazyFs.open (internal/fs/streams.js:277:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
Investigating
Now normally, from what I understand, this would just mean I've got the paths wrong. However, the file has actually been created and the first line of the log file has been written just fine
My next thought was that I must've set the fs flags incorrectly, but it was set to 'a' for append:
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
Removing Swagger Code
Now here's the weird bit: if I remove the Swagger code, the log files write out just fine and I don't get the fs exception!
This is the specific Swagger code:
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
When I comment out this code, the log file writes out just fine.
The only thing I can think that might be happening is that somehow Swagger is modifying (?) the app's working directory so that fs no longer finds the same file?
Full Code
'use strict';
var path = require('path');
var fs = require('fs');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 3100;
// I am specifically tried using path.join that I found when investigating this issue, and referencing the app path, but to no avail
const __logdir = path.join(__dirname,'./logs');
//These are date and time functions I use to add timestamps to the logs
function dateNow(){
var dateNow = new Date().toISOString().slice(0,10).toString();
return dateNow
}
function rightNow(){
var timeNow = new Date().toTimeString().slice(0,8).toString();
return "["+timeNow+"] "
};
console.info("Node Server Starting......");
console.info("Current Directory: " + __dirname)
// Here I create the WriteStreams
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
var errorsFile = fs.createWriteStream(__logdir+"/errorEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Error Log File to location: %s \nWith error description: %s',__logdir, err);
});
// And create an additional console to write data out:
const Console = require('console').Console;
var logOut = new Console(logsFile,errorsFile);
console.info("Trying to log data now!") // Debugging logging
logOut.log("========== Server Startup Initiated ==========");
logOut.log(rightNow() + "Server Directory: "+ __dirname);
logOut.log(rightNow() + "Logs directory: "+__logdir);
// Here is the Swagger portion that seems to create the behaviour.
// It is unedited from the Swagger Code-Gen tool
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
In case it helps, this is the project's file structure . I am running this project within a WSL instance in VSCode on Windows, same as I have with other projects using fs.
Is anyone able to help me understand why fs can write the first log line but then break once the Swagger code gets going? Have I done something incredibly stupid?
Appreciate the help, thanks!
Edit: Tried to fix broken images.
Found the problem with some help from a friend. The issue boiled down to a lack of understanding of how the Swagger module works in the background, so this will likely be eye-rollingly obvious to most, but keeping this post around in case anyone else comes across this down the line.
So it seems that as part of the Swagger initialisation, any scripts within the utils folder will also be executed. I would not have picked up on this if it wasn't pointed out to me that in the middle of the console output there was a reference to some PostgreSQL code, even though I had taken all reference to it out of the main index.js file.
That's when I realised that the error wasn't actually being generated from the code posted above: it was being thrown from to that folder.
So I guess the answer is don't add stuff to the utils folder, but if you do, always add a bunch of console logging...

Node isn't logging error messages to MongoDB as expected

I'm trying to create an error message/log using "winston-mongodb" while sending it to my database. In my MongoDB Compass it created a log folder as expected, but there's no data in it.
Here's my code:
index.js
require("winston-mongodb");
winston.add(new winston.transports.MongoDB({ db: "mongodb://localhost/vidly_node_js" }));
genres.js
router.get("/", async (req, res) => {
throw new Error("Could not get the genres.");
const genres = await Genre.find().sort("name");
res.send(genres);
});
I'm supposed to be getting this:
But this is what I keep getting:
What am I missing???
Also "throw new Error("Could not get the genres.")" is making the code down below in my get function "unreachable". Maybe that's the reason? If so, what do I need todo to fix it? Because it’s giving me an error that says:
TypeError: common.clone is not a function
Upagrade winston-mongodb package to version 4+ to work with latest winston
https://github.com/winstonjs/winston-mongodb/issues/108
Winston 3 and mongodb 3 support is now in the winston-mongodb 4.x branch.
winston-mongodb 3.0 is not compatible with latest winston
https://github.com/winstonjs/winston-mongodb/tree/v3.0.1
Current version supports only mongodb driver version 2.x. If you want to use winston-mongodb with mongodb version 1.4.x use winston-mongodb <1.x.

Winston does not write in the log files

Simple issue with the Winston logger for NodeJS, taking a ridiculous amount of hours to solve:
const winston = require('winston');
exports.logger = winston.createLogger({
transports: [
new winston.transports.File({
format: winston.format.json(),
level: 'info',
timestamp: true,
maxsize: 512000, // ~ 5 MB
maxFiles: 10,
filename: '../logs/info.log'
}),
new winston.transports.Console({
format: winston.format.simple(),
level: 'info'
})
]
});
Just as a funny fact, it can create the file inside the folder if it exists, but cannot create the folder if it does not exists (WTF?).
The problem is that never saves any information to the file. I tried modifying the access privileges. Nothing. No feedback received anywhere about the issue.
I may be too dumb for the documentation because nothing is covered about this but many people seem to be facing the same issue.
Ok, I just discovered the problem: depending on where the file is called from, the path will be interpreted differently.
Diagnose: The chunk I am showing was not in the project's root directory, but the main file I was executing is (and is requiring that chunk of code), and because of that the path was being interpreted from the root file's perspective.
Result: I was having my logs written right outside of my project's directory.

Slack-Winston in Node not working

Has anyone ran the code in npm for slack-wilson lately? It looks like this:
var winston = require('winston'), slackWinston = require('slack-winston').Slack;
var options = {
domain: '<domain>',
token: '<apiToken>',
channel: 'my-sweet-channel',
level: 'warn'
}
winston.add(slackWinston, options);
Then I try this:
winston.log('warn', 'Node test');
For some reason, I just can't get this to send messages to Slack. Am I missing something?
You're not missing anything but the package that you've used is out of date. I recommend you this other package winston-slacker

Unable to make query to OrientDB using Orientjs

I am trying to connect to OriendDB(v2.0.13) using Orientjs(v2.0.0) on NodeJS(v0.12.2) like so:
var OrientDB = require('orientjs');
var orientDBServer = OrientDB({
host: 'localhost',
port: 2424,
username: 'orientdb',
password: 'orientdb'
});
var database = orientDBServer.use({
name: 'thermos',
username: 'orientdb',
password: 'orientdb'
});
As soon as I make a query, for example:
database.select().from('OUser').all()
.then(function(result) {
console.log(result);
});
I'm getting this error.
Unhandled rejection OrientDB.ConnectionError [1]: Remote server closed
the connection.
at Connection.handleSocketEnd (/usr/share/adafruit/webide/repositories/my-pi-projects/Thermostat/node_modules/orientjs/lib/transport/binary/connection.js:320:9)
at Socket.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
I tried different query just to make sure I'm not doing a mistake myself and I also tried via studio and the console directly on the server which worked fine. (using the same logins...)
What can possibly cause this error?
Thanks
Update
I made a second nodejs server and now I can successully make requests on the database that is installed on the first server. I'll investigate if there is some sort of weird permission that blocks localhost or if node is missing some kind of permission...(first server is running raspbian)
I don't think you have to specify the username and password again for the use function. My database config file looks like this and it works like a charm :
var OrientDB = require('orientjs');
var server = OrientDB({
host:'localhost',
port:2424,
username: 'root',
password: 'root'
});
module.exports = server.use('databaseName');
Also, make sure that you created the database with the account you are using. Otherwise, it won't work.
If this still doesn't work, it could be a bug. I would personally try recreating the database...
After days of running in circles I finally found that if I remove another library that I am using, everything works fine... (library causing the conflict is GrovePi). I'll continue investigating to find the root of the issue. Thanks for your help Alex.

Categories

Resources