2

I'm trying to phrase access log files on my Nginx server.

For phrasing the file, I simply rename the original access log file and create a new access log file immediately so I won't miss anything.

But after replacing the file, Nginx won't log anything onto that file but works until I replace the file.

Nginx start logging again to the replaced file after I restart Nginx.

I can not see what I'm doing wrong, any help?

First bit of the PHP code

if(rename("access.log", $tempname)){ // I'm renaming the access log file
    $fp = fopen("access.log","wb"); 
    if( $fp == false ){

    }else{
        fwrite($fp,$content); // I'm creating a new access log file
        fclose($fp);
    }
    // I'm phrasing the renamed file here
}
Naveen Gamage
  • 1,844
  • 12
  • 32
  • 51
  • 1
    Not sure, but I would guess nginx keeps an open file handle for the file so it's only opened when nginx restarts? – Hugo Tunius Nov 10 '13 at 13:08
  • So I read the source code for nginx and it does look like the log file is only opened on program start and then the file handle is kept for any appending to the file. See https://github.com/nginx/nginx/blob/master/src/core/nginx.c#L280 – Hugo Tunius Nov 10 '13 at 13:17

1 Answers1

2

As I said in my comments it probably not possible to remove the file due to the nature of nginx, my suggestion would be using the same approach, but without actually removing the log file. Instead just clear it.

Pseudo Code

file = open "nginx.log", READ
new_file = open tmpname, WRITE
new_file.write file.contents
file.close
new_file.close
sys_command "cat /dev/null > nginx.log"

Or using a script

#!/bin/bash
cp nginx.log nginx.backup.log
cat /dev/null > nginx.log

This way you are not destroying the file and the file handle that nginx has will still be valid.

Hugo Tunius
  • 2,869
  • 24
  • 32