Moment not working for winston.transports.File - javascript

From the below post i got the idea to use moment with winston to change date format.
winston:how to change timestamp format
but this is working for winston.transports.Console and its not working for winston.transports.File
PFB my code :
var logger = new winston.Logger({
level: 'debug',
timestamp: function () {
return moment().format('YYYY-MM-DD hh:mm:ss')
},
transports: [
new(winston.transports.MongoDB)({
db : 'dbpath',
collection : 'Logs',
level : 'error',
capped : true,
timestamp: function () {
return moment().format('YYYY-MM-DD hh:mm:ss')
}
}),
new winston.Logger({
level: 'debug',
transports: [
new(winston.transports.File)
({ filename: 'filename' })
],
timestamp: function () {
return moment().format('YYYY-MM-DD hh:mm:ss')
}
}),
new winston.transports.Console({
timestamp: function () {
return moment().format('YYYY-MM-DD hh:mm:ss')
}
})
]
})
I am getting this in my output file:
{"level":"info","message":"info Hello","timestamp":"2018-04-16T06:42:12.819Z"}
{"level":"error","message":"error Hello","timestamp":"2018-04-16T06:42:12.847Z"}
{"level":"debug","message":"debug Hello","timestamp":"2018-04-16T06:42:12.861Z"}
{"level":"warn","message":"debug Hello","timestamp":"2018-04-16T06:42:12.900Z"}
it's neither working for mongodb transport

Related

I can't change the default `{ level: info }` in the Pino settings for Fastify

I can't change the default option - { level: info } in the Pino settings for Fastify.
The other options work as they should.
I have a project with the structure:
project/
node_modules/
plugins/
pino/
config/
config.js
dev.js
logs/
dev.log
routes/
home.js
app.js
package-lock.json
package.json
app.js
import fastify from 'fastify'
const { default: pino } = await import('./pino/config/config.js')
const app = fastify({ logger: pino.dev })
await app.register(import('./plugins/env/plugin.js'))
await app.register(import('./routes/home.js'))
await app.listen({ port: process.env.PORT || 5500 })
pino/config/config.js
const { default: dev } = await import('./dev.js')
// const { default: prod } = await import('./prod.js')
// const { default: test } = await import('./test.js')
export default {
dev,
// prod,
// test,
}
pino/config/dev.js
const targets = [
{
target: 'pino-pretty',
options: {
name: 'dev-terminal',
level: 'error', // It should be 'error', but it works as 'info' (default value)
// setting pino-pretty
colorize: true,
levelFirst: true,
include: 'level,time,',
translateTime: 'yyyy-mm-dd HH:MM:ss Z',
},
},
{
target: 'pino/file',
options: {
name: 'dev-local-file',
level: 'fatal', // It should be 'fatal', but it works as 'info' (default value)
destination: './pino/logs/dev.log',
mkdir: true,
},
},
]
export default {
transport: {
targets,
},
}
Can I do without disableRequestLogging?
The option are in the wrong order, here a working example:
const pino = require('pino')
console.log(pino.version)
const log = pino({
level: 'debug', // main log level, must be lower than the transport level
transport: {
targets: [
{
target: 'pino-pretty',
level: 'error',
options: {
name: 'dev-terminal',
colorize: true,
levelFirst: true,
include: 'level,time,',
translateTime: 'yyyy-mm-dd HH:MM:ss Z'
}
},
{
target: 'pino/file',
level: 'fatal',
options: {
name: 'dev-local-file',
destination: 'dev.log',
mkdir: true
}
}
]
}
})
log.debug('debug')
log.info('info')
log.error('error')
log.fatal('fatal')

Unable to query data with mongoose using dates (nodejs)

I'm trying to query all Assistance documents that have the "inputDate" between their startDate and endDate. I've been looking on the internet for ages and I'm unable to make it work. It is suposed to retrieve the only document that right now is in my db. I'm using NodeJS+Mongoose.
The code in the controller is the following:
exports.getOccupation = (req, res, next) => {
var inputDate = new Date("1999","10","13","16","0","0");
Assistance.find({
dateInterval:{
startDate: {$lte:inputDate},
endDate: {$gte:inputDate}
}
})
.then(assistances => {
console.log(assistances.length);
})
}
The code of the model:
const assistanceSchema = new Schema(
{
user_id:{
type: Schema.ObjectId
},
place:{
longitude:{
type:String
},
latitude:{
type:String
}
},
dateInterval:{
startDate: Date,
endDate: Date
}
},
{timestamps:true}
);
I'm not sure, but I believe that find() method accept dateInterval.startDate instead of dateInterval:{startDate: ... }.
Try change this way:
Assistance.find({
$and: [
{ "dateInterval.startDate": { $lte: inputDate } },
{ "dateInterval.endDate": { $lte: inputDate } },
],
}).then((assistances) => {
console.log(assistances.length);
});

Winston outputs json instead of formatted string

I have set up a simple winston logger in my app like this:
function logger(success, msg) {
let now = new Date().toUTCString()
let logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
filename: 'log.log',
timestamp: function() {
return new Date().toUTCString();
},
formatter: function(options) {
return `>>>>>>>>>> ${options.timestamp()} - ${options.level.toUpperCase} - ${options.message}`;
}
})
]
});
if (success) {
logger.log('info', msg)
} else {
logger.log('error', msg)
}
}
But instead of logging the formatted string, it outputs the following:
{"level":"error","message":"Nothing to upload","timestamp":"Mon, 23 Apr 2018 13:53:01 GMT"}
Ideas? Am I missing something? (Of course I am)
As you can find out in winston documentation for File you can set property json to false if you don't want information in file to be JSON objects. By default this property is true.
json: If true, messages will be logged as JSON (default true).
Could you try to change your code like this:
function logger(success, msg) {
let now = new Date().toUTCString()
let logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
filename: 'log.log',
timestamp: function() {
return new Date().toUTCString();
},
json: false,
formatter: function(options) {
return `>>>>>>>>>> ${options.timestamp()} - ${options.level.toUpperCase} - ${options.message}`;
}
})
]
});
if (success) {
logger.log('info', msg)
} else {
logger.log('error', msg)
}
}

Angular 2 get json data from url

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let ep = './data.json';
this.events = this.http
.get(ep, { headers: headers })
.map(res => res.json())
.map(({results}: { results: Data[] }) => {
return results.map((data: Data) => {
return {
title: data.title,
start: new Date(data.from),
colors.yellow,
};
});
});
Here is my code in Angular 2. I want to get data from a JSON file and show it in the angular-calendar.
Here is angular-calendar Demo: How can I do that?
You can make a service that contains the data for the calendar.
getList(): any
{
var date = new Date( '2017-01-12' );
var date2 = new Date( '2017-03-17' );
return (
[
{ title: 'Beauty And The Beast', start: date2, color: { primary: '#e3bc08', secondary: '#FDF1BA' } },
{ title: 'La La Land', start: date, color: { primary: '#e3bc08', secondary: '#FDF1BA' } }
]
)
}
Then you will have to remove the async pipe from the template.
Before:
[events]="(events | async ) || []
After:
[events]="(events) || []
Then call the service in the component:
fetchEvents()
{
this.events= this._data_Service.getList()
}
2. To get data.json file with Http you need to put the JSON file in the assets folder: ./assets/data.jsom, so that it can be accessed by the application: localhost:8080/data.json.
Then you simply make a get request.
fetchEvents(): void {
this.events = this.http
.get('../../assets/data.json') // the path may vary depending
// on your directory structure.
.map(res => res.json())
.map((results) => { // this might be different depending on
// your json and type definition.
return results.map((data: Data) => {
console.log({title: data.title,
start: new Date(data.from),
color: colors.yellow})
return {
title: data.title,
start: new Date(data.from),
color: colors.yellow,data
};
});
});
}// fetchEvents
Here is the JSON I used:
[
{"title":"La La Land","from":1490475722305},
{"title":"Beauty And The Beast","from":1490475722305}
]
finally, you can include the type definition in your component:
interface Data {
title: string;
from:string;
}
interface DataEvent extends CalendarEvent {
data: Data;
}

Add more fields in MapReduce with Mongoose and NodeJS

I've this mongoose schema
var SessionSchema = mongoose.Schema({
id: Number,
cure: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Cure'
},
performances: Array,
startDate: Date,
endDate: Date,
validatee: Boolean,
deleted: Boolean
});
I need to know how many documents have different ids, but i only need those that have startDate greater than a given date (for example today).
Running the following code works fine but i want to add some fields in map to use them in the query.
var o = {};
o.map = function () {
emit(this.id, 1
// list other fields like above to select them
)
}
o.reduce = function (k, vals) {
return vals.length
}
o.out = {
replace: 'createdCollectionNameForResults'
};
o.verbose = true;
Session.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime)
console.log("MapReduce" + JSON.stringify(model));
model.find().exec(function (err, docs) {
console.log(docs);
});
});
This is my output :
[ { _id: 0, value: 2 },
{ _id: 1, value: 4 },
{ _id: 2, value: 2 } ]
I try to do this:
....
o.map = function () {
emit(this.id, {
startDate: this.startDate
})
}
....
model.find({
startDate: {
"$gte": new Date()
}
}).exec(function (err, docs) {
console.log(docs);
});
....
but I keep getting the same output.
So how do I add more key-value params from the map function to the result dictionary of the reduce function?
This is a solution :
var o = {};
o.map = function () {
emit(this.id, {
startDate: this.startDate,
cure: this.cure,
test: 'test'
// list other fields like above to select them
})
}
o.reduce = function (k, vals) {
return {
n: vals.length,
startDate: vals[0].startDate,
cure: vals[0].cure,
test: vals[0].test
}
}
o.out = {
replace: 'createdCollectionNameForResults'
};
o.verbose = true;
Session.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime);
model.find({
'value.cure':mongoose.Types.ObjectId('52aedc805871871a32000004'),
'value.startDate': {
"$gte": new Date()
}
}).exec(function (err, docs) {
if(!err)
console.log(docs.length);
});
});

Categories

Resources