S
S
sa_fex2021-01-12 16:18:11
Node.js
sa_fex, 2021-01-12 16:18:11

How to save console logs to a separate file?

I have a Node JS Discord Bot and I need to save the logs to a separate file. How can I do that?5ffda09c53356423112165.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DimaIs, 2021-01-12
@Sayfex

You can write your own logger, which is essentially a wrapper over an entry in a file, which can then be imported anywhere, or you can use ready-made libraries with many settings, for example:
Winston
It may also be useful to read about log rotation, Winston has an extension for this :
winstion-log-rotation

A
Alexander, 2021-01-12
@BigTooth

There is a much simpler and more efficient way. In case of an error or execution of any command at the end, you can write this code:

const fs = require('fs');

    var currentdate = new Date(); 
    var datetime = "Время: " + currentdate.getDate() + "/"
        + (currentdate.getMonth()+1)  + "/" 
        + currentdate.getFullYear() + " | "  
        + currentdate.getHours() + ":"  
        + currentdate.getMinutes() + ":" 
        + currentdate.getSeconds();

    let info = `Канал: ${message.channel.id} - ${message.author.tag} забанил ${puser.user.tag} навечно, по причине ${reason}.`
    fs.appendFileSync("logs.txt","\n"+`${datetime}`+` ${info}`);

This code is an example for a ban command that outputs the event exactly as specified in the info. The file to be written must be specified; each event will be entered from a new line! The same can be done with error output! I hope you find it useful :)

R
rPman, 2021-01-12
@rPman

If you need to save the output of the application to a file, then you can run it simply by specifying redirects through the system pipes:
node myprog.js > myprog.log 2>myprog.err

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question