Winston not logging correct values - javascript

Hey everyone i need help setting up my Winston logging config.
I am migrating an existing project with 300 + console.logs to winston and now the values of the logs are not printed anymore.
I researched online and only found hacky solutions that didn't work for me.
Any help is appreciated.
This is my logger config
// logger config
const winston = require('winston')
const { combine, timestamp, colorize, align, printf } = winston.format
const logger = winston.createLogger({
// level: process.env.LOG_LEVEL || 'info',
level: 'silly',
format: combine(
colorize({ all: true }),
timestamp({
format: 'YYYY-MM-DD hh:mm:ss',
}),
align(),
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
), transports: [new winston.transports.Console()],
})
module.exports = logger
This is how the console log was before:
console.log('active jobs : ',
(await queue.getActive()).length)
Output:
active jobs : 12
This is how it is now:
logger.info(
'active jobs : ',
(await queue.getActive()).length
)
Output:
[2022-05-23 03:57:29] info: active jobs :
I would appreciate if there is a possibility without changing the console.logs since they are so many.

Related

how to download txt file with api in next.js

how is it possible to download txt with api in next.js
the console.log(ninjas) already shows the correct info
i have tested api postman and works perfect
when i use get in postman same info output as console log in code
but how do i add feature to download the file
so i get a pop up with download
new error
error ReferenceError: triggerDownload is not defined
at C:\java\node\next\test\.next\server\pages\test2.js:32:147
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
code im using
/////////////////// api scrip audiocodes
export const getStaticProps = async () => {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic password");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("http://10.0.5.26/api/v1/files/ini", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.then(result => triggerDownload(result, 'board.ini'))
.catch(error => console.log('error', error));
return {
}
}
//////////////// start website
const Backup = () => {
return (
<div>
<h>Download started</h>
</div>
);
}
export default Backup;
Output file of log console.log(ninjas)
;**************
;** Ini File **
;**************
;Time & Date: 16/08/2021 09:13:59
;Device Up Time: 48d:21h:38m:41s
;Board: UNIVERGE BX9000
;Board Type: 72
;Serial Number: 9107130
;Software Version: 7.20A.256.721
;DSP Software Version: 5014AE3_R => 723.06
;Board IP Address: 10.0.5.26
;Board Subnet Mask: 255.255.255.0
;Board Default Gateway: 10.0.5.4
;CPU: Cavium Networks Octeon V0.1 # 500Mhz, total 2 cores, 2 cpus, 1 sockets
;Cores mapping:
;core #0, on cpu #0, on socket #0
;core #1, on cpu #1, on socket #0
;Memory: 512 MB
;Flash size: 64 MB
;Num of DSP Cores: 3
;Num of physical LAN ports: 12
;Client defaults file is being used (file length=1573)
;;;Key features:;Board Type: 72 ;IP Media: VXML ;DATA features: FireWall&VPN ;PSTN Protocols: ISDN IUA=2 CAS ;Security: IPSEC MediaEncryption StrongEncryption EncryptControlProtocol ;Channel Type: RTP DspCh=150 ;HA ;Coders: G723 G729 GSM-FR G727 G722 ;DSP Voice features: IpmDetector ;Control Protocols: MSFT FEU=50 SIP SBC=25 ;Default features:;Coders: G711 G726;
;----- HW components -----
;
; Slot # : Module type : # of ports
;----------------------------------------------
; 1 : Empty
; 2 : Empty
; 3 : Empty
;----------------------------------------------
;USB Port 1: Empty
;USB Port 2: Empty
;----------------------------------------------
[SYSTEM Params]
SyslogServerIP =
EnableSyslog = 1
TelnetServerEnable = 2
ENABLEPARAMETERSMONITORING = 1
ActivityListToLog = 'pvc', 'afl', 'dr', 'fb', 'swu', 'naa', 'spc', 'll', 'cli', 'ae'
SyslogServerPort = 0
DayLightSavingTimeStart = '01:01:00:00'
DayLightSavingTimeEnd = '01:01:00:00'
DayLightSavingTimeEnable = 1
HALocalMAC = '00908f8ass'
TR069ACSPASSWORD = ''
TR069CONNECTIONREQUESTPASSWORD = ''
NTPServerIP = ''
SBCWizardFilename = 'templates4.zip'
PM_VEDSPUtil = '1,135,150,15'
I am a bit confused about why you are doing response.text(), and later doing ninjas.map, it will map on characters of a string.
assuming you edited it to see console.log or lost something while copying code from multiple files...
if you want to trigger a download dialog with custom content you can do something like this:
function triggerDownload(stringContent = '', filename = 'download.blob') {
const blob = new Blob([stringContent], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
a.click()
URL.revokeObjectURL(url)
}
triggerDownload('string, do a JSON.stringify(ninja) if object', 'config.json')
// <a onClick={()=>triggerDownload(ninja.content, `${ninja.id}.ini`)}
// <a onClick={()=>triggerDownload(ninja.content, ninja.id + '.ini')}
there is also mention of js-file-download lib and react-download-link component in a topic mentioned by #juliomalves
so this whole thing might be a duplicate, or all of my assumptions is wrong :)

Winston javascript logger is creating two separate log files. How do I log all entries into a single file?

I'm attempting to use Winston and winston-daily-rotate-file to log all my console/log output from a node.js server to a single file that will (hopefully) get rotated daily at midnight.
The issue I'm encountering is that unhandled exceptions seem to generate a new log file rather than write to the existing one. See the example code below for the duplication behaviour. How do I get all output to be saved to a single logfile as well as output to the console? At present, the console side of things appears to be fine but feel free to point out anything obvious that I'm missing.
OS: Win 10
node: v12.16.0
npm: v6.13.4
winston: v3.2.1
winston-daily-rotate-file: v4.4.2
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
var logger = new (winston.createLogger)({
transports: [
new (winston.transports.Console)({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.colorize({ all: true }),
winston.format.printf((info) => {
const {
timestamp, level, message
} = info;
return `${timestamp} - ${level}: ${message}`;
}),
),
handleExceptions: true
}),
new DailyRotateFile({
name: 'file',
datePattern: 'YYYY-MM-DDTHH-mm-ss',
handleExceptions: true,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf((info) => {
const {
timestamp, level, message
} = info;
return `${timestamp} - ${level}: ${message}`;
}),
),
filename: path.join(__dirname, 'logs', '%DATE%.log')
}),
]
});
logger.info("This is an info message");
logger.error("This is an error message");
setTimeout(() => {throw new Error('oh dear!')}, 5000);
My issue was caused by the datePattern option. winston-daily-rotate-file uses this pattern to determine the frequency of file rotation. As I had included seconds in the pattern it was looking for a file with the current timestamp (to the nearest second) and creating it before writing to file.
To get daily files I just needed to change
datePattern: 'YYYY-MM-DDTHH-mm-ss'
to
datePattern: 'YYYY-MM-DD'

NodeJs Winston log line number

I am writing a module for logging in Nodejs using Winston. I am using a custom format and initialize my logger like this:
const logger = createLogger({
format: combine(
format.timestamp(),
format.printf(msg => `${JSON.stringify({timestamp: msg.timestamp,
shortmessage: msg.message,
level: msg.level,
source: config.programName,
file: __filename,
line: '' })}`) // how to get this?
),
transports: [new (transports.Console)({
level: config.logLevel, // logs up to specified level
})]
});
module.exports = {
error: function (message) {
logger.error(message);
},
info: function (message) {
logger.info(message);
},
debug: function (message) {
logger.debug(message);
}
};
As mentioned in the comment, I also need to include line number in my log. I did some research and found some workarounds (1, 2, 3), but it seems they can't be used in my case, as I use a custom format, which should be specified during the logger creation time and line number can be retrieved later.
I was thinking to use Winston's label feature, but it seems labels can contain only static data.
How can this be solved? Any ideas.

Hiding log-level in Winston logs

I am using Winston.js to log some information in a Javascript application. The problem is that the log level should be hidden in the printed log.
Instead of having something like this:
info: some pretty and cool log message
I need to have something like this:
some pretty and cool log message
I have a look at the Winston main page, but I did not find anything.
You need to use custom format:
const { createLogger, format, transports } = require('winston');
const winston = createLogger({
level: 'info',
transports: [
new transports.Console({
level: 'info',
format: format.combine(
format.colorize(),
format.printf(
(info) => {
// return `${info.level}: ${info.message}`;
return `${info.message}`;
})
)
}),
]
});
winston.info('Hello world');
winston.log('info', 'Hello world 2');
//or you can use wrapper to easy replace console.log
const logger = {
log:(msg) => {
winston.info(msg);
}
}
logger.log('Hello world 3');
Scrabbling the unit test of the library, I found this one: Custom formatter. Basically, declaring a custom formatter for a log level, you can basically do everything you want with the text that will be write to the log.
To write the log message only without any log level information, redefine the formatter for a log in the following way.
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'info',
pattern: /info\:/,
formatter: function(params) {
return undefined !== params.message ? params.message : "";
}
})
]
});
The above example defines a console logger that prints only the message for the logs of level info, without any additional information.
Hope it helps.

Winston rotate writing to mutiple files

So Im using winston-daily-rotate-file.
In app.js I have:
var logger = require('./logger');
and then:
logger.info("logging to info");
logger.error("logging to error");
In logger/index.js I have:
var error_transport = new winston.transports.DailyRotateFile({
filename: '../logs/error',
datePattern: 'yyyy-MM-dd.',
prepend: true,
level: 'error',
name: 'error'
});
var info_transport = new winston.transports.DailyRotateFile({
filename: '../logs/info',
datePattern: 'yyyy-MM-dd.',
prepend: true,
level: 'info',
name: 'info'
});
var logger = new (winston.Logger)({
transports: [
error_transport,
info_transport
]
});
module.exports = logger;
What happens is that the file
logs/DATE_error
contains:
logging to error
BUT: the file
logs/DATE_info
contains:
logging to info
logging to error
Why is the info file also including logs from error?
You can read about Winston's logging levels here: Logging Levels
The basic reason that info is including logs from error is that "levels" with a higher priority number will always log messages for any level "below" them in priority. See the example under Using Logging Levels
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'warn' }),
new (winston.transports.File)({ filename: 'somefile.log', level: 'error' })
]
});
logger.debug("Will not be logged in either transport!");
logger.transports.console.level = 'debug';
logger.transports.file.level = 'verbose';
logger.verbose("Will be logged in both transports!");

Categories

Resources