Lax/traffic-accounting-nginx-module
Über uns
Überwacht die eingehenden und ausgehenden Traffic-Kennzahlen von NGINX in Echtzeit.
Systeme und InfrastrukturGemessener Sternzuwachs
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Verlauf wird gesammelt
Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.
README.md
Originaltraffic-accounting-nginx-module
Monitor the incoming and outgoing traffic metrics in realtime for NGINX.
Now accounting module supports both HTTP and STREAM subsystems
A realtime traffic and status code monitor solution for NGINX, which needs less memory and cpu than other realtime log analyzing solutions. Useful for traffic accounting based on NGINX config logic (by location / server / user-defined-variables).
Why?
Realtime log analysis solutions, which requires multiple machines for storage and analysis, are too heavy for application monitoring.
An cost-effective solution is in need to monitor the traffic metrics/status of application requests. This solution should be accurate, sensitive, robust, light weight enough, and not affected by traffic peaks.
How it works?
This module keeps a list of metrics identified by accounting_id in its context.
When a new request hits the server, the module will try to find its accounting_id, calculate statistics, and aggregate them into the corresponding metrics by accounting_id.
For each time period (defined by interval), a timer event is triggered, those metrics are rotated and exported to log files or sent to remote log servers.
Quickstart
Build the module into nginx from source -- the supported way to install it:
# inside the nginx source tree (grab it from nginx.org)
./configure --with-stream --add-module=/path/to/traffic-accounting-nginx-module
make && sudo make install
Turn accounting on in nginx.conf and reload with nginx -s reload:
http {
accounting on;
accounting_log logs/http-accounting.log;
accounting_id $host;
}
Every directive is described under Configuration; dynamic
builds (--add-dynamic-module, which need load_module) are covered in
Installation.
Prebuilt .so files on the Releases page: the ones attached to v3.0.0
(May 2026) are musl-linked x86-64 objects, so they cannot load into
glibc-based nginx builds (distribution packages, the official Debian image),
and that code predates the security and accounting-integrity fixes on
master. Build from source instead; the rules that decide whether a given
.so loads into a given nginx are in COMPATIBILITY.md.
Dashboard
Dashboard - Visualize with Grafana

Configuration
Edit your nginx.conf.
Example:
http{
# turn on accounting function
accounting on;
accounting_log logs/http-accounting.log;
...
server {
server_name example.com;
accounting_id $http_host; # set accounting_id string by variable
location / {
accounting_id accounting_id_str; # set accounting_id string by location
...
}
location /api {
accounting_id API_PC; # for pc
if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
accounting_id API_MOBILE; # for mobile
}
...
}
}
}
Directives
accounting
syntax: accounting on | off
default: accounting off
context: http, stream
accounting_log
syntax: accounting_log </path/to/log/file> [level]
default: -
context: http, stream
Configures logging.
Support both local file path, or stderr, or syslog:.
The second parameter is the log level.
For more details of supported params, refer to this page from nginx.org.
If not specified, accounting log will be written to /dev/log.
accounting_id
syntax: accounting_id <accounting_id>
default: accounting_id default
context: http, stream, server, location, if in location
Sets the accounting_id string by user defined variable.
This string is used to determine which metrics a request/session should be aggregated to.
accounting_interval
syntax: accounting_interval <seconds>
default: accounting_interval 60
context: http, stream
Specifies the reporting interval. Defaults to 60 seconds.
Values outside 1s .. 30d are clamped to that range (with a warning).
accounting_max_metrics
syntax: accounting_max_metrics <number>
default: accounting_max_metrics 16384
context: http, stream
Maximum number of distinct accounting_ids tracked per reporting
interval, per worker process. Once the limit is reached, further new
ids are accounted under the reserved id __overflow__ and an alert is
logged once per interval. Values outside 16 .. 1048576 are clamped
(with a warning).
Memory use is roughly 1 KB per tracked id per worker; raise the limit only if you legitimately serve more distinct ids than the default.
accounting_perturb
syntax: accounting_perturb on | off
default: accounting_perturb off
context: http, stream
Randomly staggers the reporting interval by 20% from the usual time.
Security hardening
When accounting_id is derived from request-controlled variables (for
example $http_host), the id crosses a trust boundary. Ids are
therefore normalized before they are used as metrics keys:
- ids longer than 255 bytes are truncated to their first 255 bytes;
- control characters,
DELand the field separator|are replaced by_, so exported log lines cannot be forged or misparsed; - the per-interval number of distinct ids is capped by
accounting_max_metrics.
Two ids are reserved. They share the same __name__ form, so they
are recognizable as module-generated in any dashboard, and the same
rule: a real id that happens to equal a reserved word is simply merged
into that bucket.
__default__— also the default value of theaccounting_iddirective, so all unattributed traffic is accounted in one bucket: locations without anaccounting_id, and ids that are empty or unset (for example HTTP/1.0 requests carry noHostheader, so$http_hostis unset). Such requests are never silently skipped, and the bucket always gets its own node, even past the cap.__overflow__— ids that would exceed theaccounting_max_metricscap are accounted here; an alert is logged once per interval.
Together with the per-interval cap these rules bound worker memory and export time even under adversarial traffic.
Usage
This module can be configured to writes metrics to local file, remote log server or local syslog device.
Open-source log-aggregation software such as logstash also support syslog input, which will help you establish a central log server. See samples/logstash/ for examples. [Recommended]
To collect logs with local syslog, refer Lax/ngx_http_accounting_module-utils to for sample configuration / utils.
docker / docker-compose
The demo image compiles the module (and echo-nginx-module) as dynamic
modules against the official nginx:<version>-alpine image, which ships
--with-compat, so no nginx is compiled in the build (see
COMPATIBILITY.md).
To demonstrate with docker-compose, run
docker-compose build
docker-compose up -d
Running the nginx container outside docker-compose needs
--add-host logstash:127.0.0.1: the sample configs ship metrics to the
compose-internal logstash service over syslog, and nginx refuses to
start when that hostname is unresolvable.
Restricted networks: if build containers cannot reach nginx.org /
github.com directly, copy .env.example to .env and fill
in a container-reachable proxy address (compose forwards it to the build
automatically; empty values mean "no proxy", so plain environments need
nothing). Direct docker build accepts the same values as --build-arg.
Predefined proxy args never persist into the image.
Open Grafana (address: http://localhost:3000) in your browser.
The elasticsearch datasource is provisioned automatically from
samples/grafana/datasources/. When creating it manually instead, use:
Type: elasticsearch
URL: http://elasticsearch:9200
Version: 7.10+ (the compose stack ships Elasticsearch 8.17.9)
Min time interval: 1m
Then import accounting dashboard from samples/accounting-dashboard-grafana.json.
Metrics log format
# HTTP
2018/05/14 14:18:18 [notice] 5#0: pid:5|from:1526278638|to:1526278659|accounting_id:HTTP_ECHO_HELLO|requests:4872|bytes_in:438480|bytes_out:730800|latency_ms:0|upstream_latency_ms:0|200:4872
2018/05/14 14:18:18 [notice] 5#0: pid:5|from:1526278638|to:1526278659|accounting_id:INDEX|requests:4849|bytes_in:421863|bytes_out:1857167|latency_ms:0|upstream_latency_ms:0|301:4849
# Stream
2018/05/14 14:18:22 [notice] 5#0: pid:5|from:1526278642|to:1526278659|accounting_id:TCP_PROXY_ECHO|sessions:9723|bytes_in:860343|bytes_out:2587967|latency_ms:4133|upstream_latency_ms:3810|200:9723
Each line of the log output contains metrics for a particular accounting_id,
which contains a list of key-values.
| key name | meanings of values |
|---|---|
pid |
pid of nginx worker process |
from / to |
metric was collected from the period between these timestamps |
accounting_id |
identify for the accounting unit, set by accounting_id directive |
requests |
count of total requests processed in current period (HTTP module only) |
sessions |
count of total sessions processed in current period (Stream module only) |
bytes_in |
total bytes received by the server |
bytes_out |
total bytes send out by the server |
latency_ms |
sum of all requests/sessions' $session_time, in millisecond |
upstream_latency_ms |
sum of $upstream_response_time, in millisecond |
200 / 302 / 400 / 404 / 500 ... |
count of requests/sessions with status code 200/302/400/404/500, etc. Notice the differences between http codes and stream codes |
Installation
Step 1
There are several ways to integrate traffic accounting functions into NGINX.
- Build the binaries from sources (recommended)
# grab nginx source code from nginx.org, then cd to /path/to/nginx-src/
git clone https://github.com/Lax/traffic-accounting-nginx-module.git
# to build as `static` module
./configure --prefix=/opt/nginx --with-stream --add-module=traffic-accounting-nginx-module
make && make install
# to build as `dynamic` module
# both HTTP and STREAM module, target module file name is ngx_http_accounting_module.so
./configure --prefix=/opt/nginx --with-stream --add-dynamic-module=traffic-accounting-nginx-module
# only HTTP module, target module file name is ngx_http_accounting_module.so
#./configure --prefix=/opt/nginx --add-dynamic-module=traffic-accounting-nginx-module
# only STREAM module, target module file name is ngx_stream_accounting_module.so
#./configure --prefix=/opt/nginx --without-http --with-stream --add-dynamic-module=traffic-accounting-nginx-module
make modules
Step 2 (dynamic module only)
Add the following lines at the beginning of nginx.conf:
# for combined or HTTP-only build
load_module modules/ngx_http_accounting_module.so;
# for Stream-only build
#load_module modules/ngx_stream_accounting_module.so;
Step 3
http {
accounting on;
accounting_log logs/http-accounting.log;
accounting_id $hostname;
...
}
stream {
accounting on;
accounting_log logs/stream-accounting.log;
accounting_id $hostname;
...
}
Visualization
Visualization with Kibana or Grafana is easy.
See samples/ for examples.
Supported nginx versions
CI verifies the current stable, mainline and previous stable lines of nginx on every change, tracks upstream releases daily (upstream-sentinel), and night-builds against the nginx development tip. The supported window, the compatibility policy and the dynamic-module (.so) rules are documented in COMPATIBILITY.md.
Branches
- master : main development branch.
- tag v0.1 or v2-freeze-20110526 : legacy release. works with nginx version(0.7.xx, 0.8.xx), nginx 0.9 is not tested. didn't work with nginx above 1.0.x.
Contributing
- Fork it ( https://github.com/Lax/traffic-accounting-nginx-module/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
Author
Liu Lantao Github@Lax
Contributors
Code Contributors
This project exists thanks to all the people who contribute. [Contribute].
Financial Contributors
Become a financial contributor and help us sustain our community. [Contribute]
Individuals
Organizations
Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]
License
Ähnliche Projekte entdecken
Wird geladen…