Escape slashes in log output for JSON format

kay nginx-forum at nginx.us
Mon Nov 24 14:28:24 UTC 2014


I would like to add "json" option for additional escape for backslash
character. So it will be:
access_log path format json;

The initial patch for 1.6.2 looks like:
--- ./src/http/modules/ngx_http_log_module.c.orig
+++ ./src/http/modules/ngx_http_log_module.c
@@ -67,6 +67,7 @@
     time_t                      disk_full_time;
     time_t                      error_log_time;
     ngx_http_log_fmt_t         *format;
+    ngx_uint_t                  json;
 } ngx_http_log_t;
 
 
@@ -881,7 +882,7 @@
 
     value->escape = len ? 1 : 0;
 
-    return value->len + len * 3;
+    return value->len + len * 4;
 }
 
 
@@ -951,6 +952,7 @@
     while (size) {
         if (escape[*src >> 5] & (1 << (*src & 0x1f))) {
             *dst++ = '\\';
+            *dst++ = '\\';
             *dst++ = 'x';
             *dst++ = hex[*src >> 4];
             *dst++ = hex[*src & 0xf];
@@ -1068,6 +1070,7 @@
     log->script = NULL;
     log->disk_full_time = 0;
     log->error_log_time = 0;
+    log->json = 0;
 
     lmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_log_module);
     fmt = lmcf->formats.elts;
@@ -1087,6 +1090,7 @@
 
     ssize_t                     size;
     ngx_int_t                   gzip;
+    ngx_int_t                   json;
     ngx_uint_t                  i, n;
     ngx_msec_t                  flush;
     ngx_str_t                  *value, name, s;
@@ -1189,6 +1193,7 @@
     size = 0;
     flush = 0;
     gzip = 0;
+    json = 0;
 
     for (i = 3; i < cf->args->nelts; i++) {
 
@@ -1255,6 +1260,16 @@
 #endif
         }
 
+        if (ngx_strncmp(value[i].data, "json", 4) == 0)
+        {
+            s.len = value[i].len - 5;
+            s.data = value[i].data + 5;
+
+            json = 1;
+
+            continue;
+        }
+
         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                            "invalid parameter \"%V\"", &value[i]);
         return NGX_CONF_ERROR;
@@ -1267,6 +1282,10 @@
         return NGX_CONF_ERROR;
     }
 
+    if (json) {
+        log->json = 1;
+    }
+
     if (size) {
 
         if (log->script) {

But I can't figure out how can I pass the json variable directly to the
functions:
* ngx_http_log_variable_getlen
and
* ngx_http_log_variable

Can someone give me suggestions?

Posted at Nginx Forum: http://forum.nginx.org/read.php?2,255071,255071#msg-255071



More information about the nginx mailing list