Custom logging under pm2

I have a useful registration in my node application, which I write on console.log

 node server.js >> /var/log/nodeserver.log 2>&1 

However, when trying to do the same with pm2 :

 pm2 start server.js >> /var/log/pm2server.log 2>&1 

only pm2 startup information is displayed in the log file

Is application logging possible with pm2 ? On their page, they discuss logging and display an image with text like "log message from echo.js" , but I see nothing about how to get user information in the pm2 log .

+10
logging pm2
source share
4 answers

When working with pm2, your application logs will be in $HOME/.pm2/logs , as described here . Checking this locally with a simple index.js file that console.log('test') prints

 $ pm2 start index.js [PM2] Spawning PM2 daemon [PM2] PM2 Successfully daemonized [PM2] Starting index.js in fork_mode (1 instance) [PM2] Done. ┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬────────────┬──────────┐ │ App nameidmode │ pid │ status │ restart │ uptime │ memory │ watching │ ├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼────────────┼──────────┤ │ index0 │ fork │ 36976online00s │ 9.258 MB │ disabled │ └──────────┴────┴──────┴───────┴────────┴─────────┴────────┴────────────┴──────────┘ Use `pm2 show <id|name>` to get more details about an app 

Note that there is no console.log output , but if I go to $HOME/.pm2/logs , I see

 logs $ ls index-error-0.log index-out-0.log logs $ cat index-out-0.log test 
+11
source share

A great function is to use the logs function in the terminal:

 pm2 logs [--raw] 

this will broadcast all the logs. Other convenient commands:

  • pm2 flush
  • pm2 reloadLogs
+5
source share

Update in 2017.

Defining the log path as a parameter when the pm2 ( -l , -o , -e ) command is executed is very easy to use and is usually the best choice.

However, if you do not want to determine the log path every time pm2 is executed, you can create a configuration file, define error_file and out_file , and then run pm2 from this:

  • Create a configuration file: pm2 ecosystem simple . This will create an ecosystem.config.js file with the following contents:

     module.exports = { apps : [{ name : "app1", script : "./app.js" }] } 
  • Define error_file (for the error log) and out_file (for the information log), for example:

     module.exports = { apps : [{ name : "app1", script : "./app.js", error_file : "./err.log", out_file : "./out.log" }] } 
  • Run the process from the configuration file:

     pm2 start ecosystem.config.js 

Thus, the logs are saved in ./err.log and ./out.log .

See the document for more details.

+2
source share

In the case of a new start, you simply:

  • run pm2 start/reload ecosystem.config.js [--only your_app]

But when it is already running (pm2 already controls it), you need to do (someone might find a better way, but this works for me):

  • run pm2 delete your_app
  • start pm2 start
0
source share

All Articles