NaviServer Programmable Web Server

ns_accesslog(n)

NaviServer Module Commands – 5.2.0a


[ Main Table Of Contents | Table Of Contents | Keyword Index ]

Name

ns_accesslog - Query and control access log parameters

Table Of Contents

Synopsis

Description

This command controls and configures the access log of the server. The access log records all served requests of a server containing timestamp, IP address of the requester, the queried resource, the HTTP result code, the transmitted amount of data, etc. In general, it follows the more or less standardized access log file format (NCSA format, common log format) but can be influence to contain more information, useful for log file analysis, debugging and statistics.

In most cases, the access log is controlled via the parameter specified in the configuration file (see below). For example, when the server is running in reverse proxy mode, the value provided by the reverse proxy server via request header fields will be reported in the log file instead of the IP address of the physically connected host. Several parameters can be queried and altered as well at run-time via the command ns_accesslog.

COMMANDS

ns_accesslog extendedheaders ?headers?

Return a list of the HTTP header fields which will be appended to each entry in the access log. If headers is given it replaces the existing setting.

By default, all specified header fields are request header fields (like e.g., {Referer x-forwarded-for}). Optionally one can specify the request header fields with a prefix "request:" or "response" to denote request or response header fields. The prefix can be abbreviated to 3 characters (example: {req:Host response:content-type}). Note that always the request header fields are reported before the response header fields. Caveat: certain response header fields (e.g., "Date" or "Server" are not accessible this way).

ns_accesslog file ?filepath?

Sets or gets the filepath of the access log. When filepath is not provided, the command teturns the path of the access log for the current virtual server.

If filepath is given then the old log is closed and the log re-opened at the new location. All the components of filepath must exist. If an error occurs logging will be disabled.

ns_accesslog flags ?flags?

Returns a list of the enabled logging options, or reset the list if a new set of flags is given. Valid flags are: logcombined, formattedtime, logpartialtimes, logreqtime, checkforproxy, and suppressquery. They have the same meaning as the similarly named configuration parameters.

ns_accesslog maxbackup ?nrfiles?

Sets or gets the number of backup files which will be kept when log rolling is enabled. If nrfiles is given it replaces any existing value.

ns_accesslog maxbuffer ?nrlines?

Sets or gets the maximum number of lines to buffer before being flushed to the log file.

ns_accesslog roll ?filepath?

Rolls the access log (see ns_rollfile for details). Keep maxbackup old log files around. If filepath is given then it overrides the configuration parameter file as the new log file.

ns_accesslog rollfmt ?timeformat?

Sets of gets the timeformat which is appended to the log filename when rolling. The format string is as understood by the Tcl clock command. If timeformat is given then it replaces any existing value.

ns_accesslog scan open ?-filename value? ?-format auto|common|combined? ?-timingcolumn value? ?-requesttime auto|true|false? ?-extendedheaders value? ?-tail value? ?-encoding value? ?-offset value? ?-endoffset value? ?-checkpoint value? ?-maxlinebytes integer?

Open an interpreter-local scanner of a regular access-log file. The returned opaque handle cannot be reconstructed from its string label. The scanner captures a fixed file-size snapshot; appends are read by opening another scanner from the last committed checkpoint. Scanning does not flush or otherwise change the logger. Batch scans require an already loaded, batch-capable nsdb module, but no driver, pool or connection. Ordinary logging remains independent of nsdb; scanning never loads a database module implicitly.

Options in this initial producer implementation are:

  • -filename path: defaults to this module's current log.

  • -format auto|common|combined: for the current log, defaults to its logcombined flag; for historical files, defaults to auto. Explicit auto always enables recognition from the record contents. Automatic recognition distinguishes an initial five-number timing field from two combined header fields, but historical quoted extension fields can be ambiguous.

  • -timingcolumn auto|none|0|2: for the current log, defaults to none when logpartialtimes is disabled, otherwise the timing column for the selected format. Historical files default to auto. Explicit columns count quoted fields after the byte count, excluding a bare request time. The five partial times follow producer order: start, accept, queue, filter, run. Driver-generated phase counters are unavailable worker measurements.

  • -requesttime auto|true|false: defaults to the current log's logreqtime flag, or auto for historical files. True expects a bare numeric request time following the common/combined fields; false does not consume one.

  • -extendedheaders auto|headerList: defaults to the current log's effective extended-header configuration, or auto for historical files. An explicit list uses the logger's plain request names or request:/response: tags (including req:/res: abbreviations). Names are normalized into request-then-response output order. An empty list declares no extensions; auto leaves their number and names unknown. A header named auto can be specified as request:auto. Known trailing header fields are excluded from format/timing recognition and must be quoted. Their names appear in source metadata under extraheaders; extendedFields still retains the original lexical text, without adding dynamic columns or converting header values.

  • -offset bytePosition: defaults to zero and must be at a record boundary. -checkpoint value resumes validated state instead; the two options are mutually exclusive.

  • -endoffset bytePosition: exclusive byte limit, between the starting offset and the file size captured at open. Defaults to the captured file size. Appends before or after open do not extend this limit; scanner and batch metadata report the effective limit as snapshotEnd. A limit inside a record leaves that record pending with its original safe offset. With -tail final, an interior limit must be a complete record boundary. Checkpoints retain their existing safe-offset and source/configuration checks; they do not freeze this per-open limit. Supply -endoffset again when resuming to retain or extend a bound; omitting it captures the new file size.

  • -encoding utf-8: only strict UTF-8 is supported initially. Invalid source bytes produce bounded hexadecimal diagnostic excerpts.

  • -maxlinebytes n: defaults to 65536, with supported values 128 through 1048576. Oversized lines are discarded incrementally with a bounded retained prefix, then emitted as diagnostic records covering their complete span.

  • -tail pending|final: defaults to pending. An unterminated last line remains unaccounted for in pending mode. Final mode emits it for a completed immutable input file; appending to such a finalized partial line is not a supported continuation boundary.

Current-file defaults are selected by device/inode identity, including when -filename names an alias of the current file. Flags and effective header names are copied when the scanner opens, so later logger changes do not alter an existing scanner. Explicit scanner options override their respective defaults. Checkpoints record the effective layout and header names; resuming with different settings is rejected. Current settings cannot describe older records written under different configurations in the same file: use explicit auto options or the known historical layout when scanning such data. Timestamp spelling and the thread-name placeholder are recognized from each record; query suppression, masking and proxy handling are already reflected in the logged values.

ns_accesslog scan next ?-maxrecords integer? ?-maxbytes integer? ?-maxscanbytes integer? ?-timeout time? handle

The handle is a scanner returned by ns_accesslog scan open. The original handle-first form, with options after the handle, is also accepted. Return an opaque, immutable lexical batch backed by compact shared-schema C storage. Scanning frames and decodes fields but does not convert source numbers or timestamps to native database types. Original numeric spellings, including trailing decimal zeros and values beyond native integer ranges, remain available to a later sink. The sink must enforce schema constraints before insertion.

-maxrecords defaults to 512 and permits 1 through 1000000 records, including diagnostics. -maxbytes defaults to 8388608 and limits retained value payload; fixed cell/reference capacity, metadata, source buffers and allocator overhead are additional. To guarantee progress it must allow at least four times maxlinebytes plus 2048 bytes. -maxscanbytes defaults to 16777216 and limits examined input bytes. The two byte limits permit positive values through 1073741824. -timeout defaults to 100ms (cooperative checks, not a hard deadline); supported values are 1 microsecond through one hour.

Every successful call returns a batch, even when it has zero rows. Metadata state is ready (a batch limit), budget (scan byte/time limit), snapshot-end (fully accounted for snapshot) or pending (unfinished final line). Framing state survives budget calls. Only emitted records advance safe coverage. Metadata and checkpoints do not commit anything: applications must account for records and persist the checkpoint atomically in their later database transaction. After a scan error, reopen from the last successfully accounted-for checkpoint rather than assuming the failed call delivered its speculative progress.

ns_accesslog scan info handle

The handle can be a scanner or a batch. For a scanner, report source identity, captured snapshot end, consumed read offset, safe record offset and state. A closed scanner reports closed. Read position can be ahead of safe position while a partial line is retained; internal file reads can additionally prefetch snapshot bytes.

For a batch, report batchVersion, representation compact-schema-lexical, producer, views, schema, rows, payloadBytes, storageBytes, source, coverage, checkpoint, state and diagnostic counts. The shared schema has ID naviserver.accesslog.scan, version 1, with ordered JSON base types, refinements, nullability and source representations. Its columns cover offsets, timestamp text, peer/thread/request identity, user/request/method/target/queryless path/protocol, status/bytes, combined headers, request/phase times, source/driver/pool, timing availability, raw extension fields and parse diagnostics. Timestamp text retains epoch or calendar syntax; date/time interpretation and range checks belong to the sink. Unrecognized extension fields remain raw text rather than guessed columns.

storageBytes describes batch/cell/arena capacity, excluding Tcl metadata, wrappers, the shared schema and allocator bookkeeping; it is not process RSS. Metadata inspection does not materialize record Tcl objects. Returning or modifying a Tcl metadata dictionary cannot change the underlying batch.

Checkpoints are versioned Tcl values containing file device/inode, offset, prefix and boundary anchors, and parser configuration. Resume validates identity, anchors and configuration. Truncation and supported rotation/replacement cases are detected; this assumes append-only input between snapshots and does not prove that an arbitrary in-place rewrite never occurred. A renamed open file remains readable through the original descriptor. Checkpoints must be saved as complete Tcl values, including their binary anchor fields.

ns_accesslog scan triples ?-offset integer? ?-limit integer? batch

Materialize JSON triples on demand for selected rows. The original batch-first form, with options after the batch, is also accepted. Options are -offset integer and -limit integer, both nonnegative integers. Defaults are row offset zero and limit 512; zero limit gives an empty view. The result is a canonical ns_json root-wrapped array of object triples. Names/type atoms and the schema are shared; view value objects are created only for the requested rows. Null, empty string and a literal null string remain distinct. Numbers remain lexical Tcl strings. The view can be emitted with ns_json value. Complete eager views can be expensive and are not a mandatory native-ingestion step.

The batch wrapper and scalar access interface are shared with nsdb. Batch info and triples access delegate to that interface; the producer's compact C storage layout remains private and is adopted without copying row values. Use ns_db batchinfo and ns_db batchinsert for backend-independent inspection and insertion. System-log scanning, nested scalar/container storage and a schema-associated dictionary import/view are not implemented by this stage.

ns_accesslog scan close handle

Close the descriptor of the scanner handle. Repeated close is harmless; next on a closed scanner fails. Batches already returned remain readable after close. Unreferenced scanner wrappers close their descriptors automatically, and interpreter deletion closes all its remaining scanners. Scanner and batch handles are interpreter-local; cross-thread/interpreter transfer and reconstruction from strings are unsupported.

Scanner-specific errors use the NS_ACCESSLOG SCAN error-code prefix with OPEN, OPTION, BOUNDARY, CHECKPOINT_MISMATCH, SOURCE_CHANGED, CLOSED, HANDLE, OWNER, LIMIT or UNAVAILABLE details. Ordinary option parsing may return Tcl argument errors. Shared batch validation uses NS_DB BATCH error codes. The existing logger control commands are unaffected.

CONFIGURATION

The nslog module is loaded per-server.

 ns_section "ns/server/server1/modules" {
   ns_param   nslog   nslog.so
 }
 ns_section "ns/server/server1/module/nslog" {
   ns_param file              access.log
   ns_param logthreadname     true
   ns_param logpartialtimes   true
   ns_param slowlogfile       slow-requests.log
   ns_param slowlogconntime   3s
   ns_param slowlogfiltertime 1s
   ns_param slowlogqueuetime  500ms
 }

The following are valid configuration parameters:

checkforproxy

If true then the value of the x-forwarded-for HTTP header is logged as the IP address of the client. Otherwise, the IP address of the directly connected host is logged. Default: false.

The parameter

checkforproxy

is deprecated in favor of the more general reverse proxy mode of the server.

driver

Name of the driver initiating the requests. This option can be used to produce different access logs for requests submitted via different drivers to sort out e.g. local server talk. Per default, every request is logged. When a value is provided, only requests are logged in this log file when the request comes from a driver matching the provided glob pattern.

file

String: path to the log file. Default: access.log

extendedheaders

A space separated list of additional HTTP headers whose values should be logged. Default: no extra headers are logged.

formattedtime

If true, log the time in common-log-format. Otherwise log seconds since the epoch. Default: true.

logcombined

If true, log the referrer and user-agent HTTP headers (NCSA combined format). Default: true.

logpartialtimes

If true then include the high-resolution start time of the request together with partial request durations (accept, queue, filter, run) in the access log. Default: false.

logreqtime

If true then log the total amount of time the request took to run in seconds and milliseconds. Default: false.

masklogaddr

Mask IP address in log file for GDPR (similar to the "anonip" IP anonymizer of the Swiss privacy foundation). When this parameter is set, all IP addresses are masked in the log file, such that the host-specific (= person-specific) information is masked out and the IP address does not match a particular individual anymore. Still, with the masking turned on, reverse DNS lookup and/or geolocation is possible. Default: false.

maskipv4

Mask to be used for IPv4 addresses, when masklogaddr is true. Default: 255.255.255.0

maskipv6

Mask to be used for IPv6 addresses, when masklogaddr is true. Default: ff:ff:ff:ff::

maxbuffer

The number of log entries to buffer before flushing to the log file. Default: 0.

maxbackup

Number of old log files to keep when log rolling is enabled. Default: 100.

rolllog

If true then the log file will be rolled. Default: true.

rollfmt

Specifies the a suffix for the file when it is rolled (timestamp based file naming). The format is provided via the Tcl format codes for timestamp, such, as e.g., %Y-%m-%d. Default: ""

rollhour

The hour of the day (0-23) to roll the log file if log rolling is enabled. Default: 0 (midnight).

rollonsignal

If true then the log file will be rolled when the serve receives a SIGHUP signal. Default: false.

slowlogfile

Optional additional access log for slow requests. Relative paths are resolved against the server log directory, as for file. Setting a nonempty filename enables this log. It must differ from the main access-log filename. The same formatted record is written to both logs, including all configured formatting, masking, header, thread-name, and timing options. The slow log is written without the main log's maxbuffer delay. Both logs rotate on the same schedule, signal, or ns_accesslog roll, using the same rollfmt and maxbackup. Default: disabled.

This brings the long-call monitoring practice from OpenACS to plain NaviServer. A request is selected when any configured threshold below is exceeded. Omitted thresholds are disabled; zero is a valid threshold. Selection does not require logpartialtimes. For analysis and request correlation, enable logpartialtimes and logthreadname; the connection thread name includes the pool and request identifier.

slowlogconntime

Time spent in the connection thread: filter time plus runtime, excluding accept and queue time. Accepts NaviServer time values such as 3s. Default: disabled.

slowlogfiltertime

Filter-time threshold, for example 1s. Default: disabled.

slowlogqueuetime

Queue-time threshold, for example 500ms. Default: disabled.

suppressquery

If true then the query (everything after the ? in the URL) is not logged. Default: false.

EXAMPLES

The path of the active access log.

nscp:1> ns_accesslog file
/home/ns/servers/server1/modules/nslog/access.log
 
nscp:2> ns_modulepath server1 nslog access.log
/home/ns/servers/server1/modules/nslog/access.log

The access log can be rolled manually.

nscp:1> ns_accesslog roll

Extended logging options can be configured at run-time.

nscp:1> ns_accesslog flags
logCombined
 
nscp:2> ns_accesslog flags {logcombined formattedtime}
logcombined formattedtime
 
nscp:3> ns_accesslog extendedheaders
 
nscp:4> ns_accesslog extendedheaders {Cookie Accept}
Cookie Accept

Example for writing multiple access logs per driver for a single server: In this example, the loopback traffic is written to a separate log file.

 #
 # Configure extra nssock driver for loopback traffic
 #
 ns_section "ns/modules" {
   ns_param loopback  ${bindir}/nssock
 }
 
 ns_section ns/module/loopback {
   ns_param	defaultserver	$server
   ns_param	address		127.0.0.1
   ns_param	port		8888
 }
 
 #
 # Load nslog modules twice with different names
 #
 ns_section ns/server/${server}/modules {
   ns_param	nslog		${bindir}/nslog
   ns_param	nslog2		${bindir}/nslog
 }
 
 #
 # Configure driver patterns (default "*")
 #
 ns_section ns/server/${server}/module/nslog2 {
   ns_param	file	  ${logroot}/access-loopback.log
   ns_param	driver 	  "loopback"
 }
 ns_section ns/server/${server}/module/nslog {
   ns_param	file	  ${logroot}/access.log
   ns_param	driver 	  "ns*"
 }

See Also

ns_log, ns_rollfile

Keywords

ipaddress, logging, module, nslog, path, reverse proxy, server built-in