Winston: No log files are being created

Created on 26 May 2016  ·  27Comments  ·  Source: winstonjs/winston

OS: Ubuntu 14.04
NodeJS: 6.2.0
Winston: 2.2.0

The following code does not create a log file:

const logger = new Winston.Logger({
    level: 'verbose',
    transports: [
      new Winston.transports.Console({
        timestamp: true
      }),
      new Winston.transports.File({
        filename: 'app.log',
        timestamp: true
      })
    ]
  });

logger.info('Holla');

It logs to the terminal fine:

2016-05-26T13:11:49.927Z - info: Holla

But no log file created.

Most helpful comment

I just ran into this issue. The directory has to exist first. winston will create new files for you, but it doesn't appear to create new directories for you (e.g., you need to create the "logs" directory if you are trying to log in a file located at logs/app.js)

All 27 comments

+1

+1

+1

+1

It seems problem in node 6 in fs.stat()
On a some reason never executed callback fs.stat()

    fs.stat(fullname, function (err, stats) {
      if (err) {
        if (err.code !== 'ENOENT') {
          return self.emit('error', err);
        }
        return createAndFlush(0);
      }

      if (!stats || (self.maxsize && stats.size >= self.maxsize)) {
        //
        // If `stats.size` is greater than the `maxsize` for
        // this instance then try again
        //
        return self._incFile(function() {
          checkFile(self._getFile());
        });
      }

      createAndFlush(stats.size);
    });
  })(this._getFile()); 

Is it fixed?

I fixed this problem my giving the absolute path like that:
winston.add(winston.transports.File, { filename:${__dirname}/logs/appError.log})

This is working for me. I did have an issue recently on a project with Winston using Atom where the .gitignore files were not showing in the file directory of the project in Atom because of an updated setting in the tree-view package... (Option: Hide VCS Ignored Files)

_Using Node 6.2.2 and Winston 2.2.0._

Code:

'use strict';

let Winston = require('winston');


const logger = new Winston.Logger({
    level: 'verbose',
    transports: [
      new Winston.transports.Console({
        timestamp: true
      }),
      new Winston.transports.File({
        filename: 'app.log',
        timestamp: true
      })
    ]
  });

logger.info('Holla');

Creates an app.log file with output: {"level":"info","message":"Holla","timestamp":"2016-07-01T19:29:14.035Z"} and logs to console with 2016-07-01T19:29:14.034Z - info: Holla

I just ran into this issue. The directory has to exist first. winston will create new files for you, but it doesn't appear to create new directories for you (e.g., you need to create the "logs" directory if you are trying to log in a file located at logs/app.js)

Wish winston checked if the log folder/directory exists , then creating a log folder/directory should it not exist during startup. I think fs can do this right?

+1

+1

+1

if (!fs.existsSync('path') {
    fs.mkdirSync('path');
}

http://thisdavej.com/using-winston-a-versatile-logging-library-for-node-js/

I was having this problem and solve it using double slashs:

        Logger.loggerInfo = new Winston.Logger({
            level: 'info',
            transports: [
                new Winston.transports.File({
                    filename: process.cwd() + '\\logs\\info.log',
                    timestamp: true
                })
            ]
        });

I made severals tests with severals advanced logging mechanisms (incl. winston) and it appears that loggers are not able to write into file if you do a clean exit (process.exit(0)).
Removing clean exit solve the problem.

@fvuilleumier you're right, thanks, however removing is not convenient for CLI tools for eg. But using process.exitCode = 0 (or any code) works perfectly because it allows the loop to finish gracefully.

There is an example for creating a file

const filename = path.join(__dirname, 'created-logfile.log');

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename })
  ]
});

create file example

@fvuilleumier @nicosommi but what about if I want to exit the application after it has logged an error? Did you manage to find a walk around?

@danbrownbox at the end of the day a js script is just a file that gets executed till the end, so if you want to exit the application after some particular line you just need to build the proper execution flow on your function

Doesn't work with relative path on my mac, but creates file if absolute path is provided.

Whether I'm using absolute or relative it doesn't matter. It's not working for me when adding the transport dynamically.

function createLogFile(appName) {
  pathUtils.ensureDirectoryExists('logs');
  pathUtils.ensureDirectoryExists(`logs/${appName}`);
  winston.add(winston.transports.File, {
    level: 'debug',
    //filename: `logs/${appName}/export-${Date.now()}.log`,
    //filename: `${__dirname}/logs/${appName}/export-${Date.now()}.log`,
    filename: `${process.cwd()}/logs/${appName}/export-${Date.now()}.log`,
    json: false,
    formatter: _formatLog()
  });
}

However, if I add this transport in createLogger() it works with absolute.

This answer works for me.
Here is my code:
````
const winston = require('winston');
const logDir = 'logs';
const fs = require('fs');

if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}

const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
exitOnError: false,
transports: [
new (require('winston-daily-rotate-file'))({
filename: ${logDir}/logs.log,
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
level: 'silly'
}),
new (require('winston-daily-rotate-file'))({
filename: ${logDir}/errors.log,
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
level: 'error'
})
],
});

export {logger};

logger.silly('silly test');
logger.info('info test');
logger.warn('warn test');
logger.error('error test');
````

I'm the original author of this issue (different account). I'm back ... because I have the same problem and I forgot how I resolved it 🤣

Are you using latest [email protected]? Did you make sure the directory exists where you want the log file to be (winston won't create dirs for you, though we'd accept a PR making that an option or even the default behavior). We should probably close this old issue once we can get you up and running again :)

I'd be willing to work on a PR for this in my spare time so leave it with me 👍

Cool! 👍 Going to close this, we can track the directory stuff in #1465 . Separate issues should be tested against master and opened as new issues if problems persist. Thanks!

Was this page helpful?
0 / 5 - 0 ratings