-2

I want to write into a txt file all the logs of my nodeJs program.

I'm using node script-file.js >log-file.txt, but it overwrites the same txt file every time it runs.

Is there a parameter to add so that the title of the generated log-file.txt includes the date and time like this : log-file-18-06-2010-11-57 (dd-mm-yyyy-hh-mm)?

4
  • Give winston a try!
    – Rayon
    Jun 18, 2021 at 10:05
  • 1
    > = overwrite, >> = append.
    – tevemadar
    Jun 18, 2021 at 10:07
  • Thank you @tevemadar, but I'd rather have it generate a new document with the time and date than continue writing to the same file
    – Yacine P
    Jun 18, 2021 at 13:29
  • How about this one? stackoverflow.com/questions/7727114/…
    – tevemadar
    Jun 18, 2021 at 13:54

2 Answers 2

3

Thanks to a friend of mine, I was able to answer my question.

As the solution node script.js > log.txt 2> errors.txt generates only one file of logs and one file of errors. Putting >> instead of > permit to append the logs and errors, but the notion of time is lost.

The SOLUTION is to simply do node script.js >> log-error.txt 2>&1 and it generates one file, where both logs and errors are transcribed into this file. You have to console.log the date at the top of the script and it makes a reliable log-errors file. To add the date (it will help beginners) just write this : var today = new Date(); console.log(today.getDate() + '-' + today.getMonth() + '-' + today.getFullYear() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds() + '.' + today.getMilliseconds())

1

How about using package? I think this is very simple way. Here's the awesome log file package

1
  • I tried the "log file package", but it only writes what we put between brackets. If we put log('Some data'); we will have a default.log file generated with only "Some data" written in it. I'm looking to copy the logs on the terminal (the console.logs and the errors) on this document
    – Yacine P
    Jun 18, 2021 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.