Server.log using fs.appendFile won't work

Hi there!

I’m a novice trying to make a server.log file in a node app built on Express (see code below). Unfortunately server.log won’t show up in the folder. Maybe the File System works different when used locally than on Glitch?

app.use((req, res, next) => {
var now = new Date().toString();
var log = ${now};
console.log(log);
fs.appendFile(“server.log”, log + “\n”, (err) => {
if (err) {
console.log(“Unable to append to server.log”);
}
});
next();
});

That’s because files created in the code don’t actually sync with the project editor. Typing refresh in the Glitch Console should do the trick!

Thanks mate! It didn’t work out unfortunately.

Here is a link if you wan’t to have a look,

By default, server.log is ignored by git, and the editor doesn’t show gitignored files.

FYI you may have issues in the file if a request starts appending before another append has finished … or maybe it will be fine! :slight_smile:

Oh wait, something similar just happened to me. When I tried to add a server.log, it didn’t show up and when I tried to add it as a new file, it said it was gitignored, although I didn’t have one. So here is how you fix it:

  1. Create a .gitignore file if you don’t have one.
  2. In the gitignore, type !server.log
  3. Type refresh in the Glitch Console to restart the project.

It isn’t a good idea to include log files in the git repo, as each change adds another version and increases disk usage at a faster rate.

Another way to make the log more accessible is to serve it from the server script.

How? Because I’m using the Winston package to record logs into a server.log file and some of the logs are very long.

Simplest solution of showing the whole file on request …

const fs = require("fs");

// show full file
app.get("/show", function(req, res) {
  var file = fs.createReadStream('combined.log', {encoding: 'utf8'});
  file.pipe(res);
});

There are fancier solutions out there, it’d take a bit of research to work out what fits your web app.

So there’s no need for ungitignoring the log files?

Thanks guys! Now I can see my log file and I understand why it should not be in the git repo :slight_smile: I will let it be excluded except for when I want to have a look in it.