Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

PSR-15 middleware to generate access logs

License

NotificationsYou must be signed in to change notification settings

middlewares/access-log

Repository files navigation

Latest Version on PackagistSoftware LicenseTestingTotal Downloads

Middleware to generate access logs for each request using theApache's access log format. This middleware requires aPsr log implementation, for examplemonolog.

Requirements

Installation

This package is installable and autoloadable via Composer asmiddlewares/access-log.

composer require middlewares/access-log

Example

useMonolog\Logger;useMonolog\Handler\StreamHandler;//Create the logger$logger =newLogger('access');$logger->pushHandler(newStreamHandler(fopen('/access-log.txt','r+')));$dispatcher =newDispatcher([newMiddlewares\AccessLog($logger)]);$response =$dispatcher->dispatch(newServerRequest());

Usage

This middleware usesPSR-3 logger standard to store the logs, so you need to pass aPsr\Log\LoggerInterface instance to the constructor.

format

This option allows to define the format used to save the log messages. You can create your own format (More info about the available options) ou use one of the following constants provided with predefined formats:

  • AccessLog::FORMAT_COMMON (Used by default)
  • AccessLog::FORMAT_COMMON_VHOST
  • AccessLog::FORMAT_COMBINED
  • AccessLog::FORMAT_REFERER
  • AccessLog::FORMAT_AGENT
  • AccessLog::FORMAT_VHOST
  • AccessLog::FORMAT_COMMON_DEBIAN
  • AccessLog::FORMAT_COMBINED_DEBIAN
  • AccessLog::FORMAT_VHOST_COMBINED_DEBIAN
useMiddlewares\AccessLog;$format = AccessLog::FORMAT_COMMON_VHOST;$accessLog = (newAccessLog($logger))->format($format);

ipAttribute

By default uses theREMOTE_ADDR server parameter to get the client ip. This option allows to use a request attribute. Useful to combine with any ip detection middleware, for exampleclient-ip:

Dispatcher::run([//detect the client ip and save it in "ip" attribute    (newMiddlewares\ClientIP())->attribute('ip'),//use that attribute    (newMiddlewares\AccessLog($logger))->ipAttribute('ip')]);

hostnameLookups

Enable thehostnameLookups flag used to get the remote hostname (%h). By default isfalse.

context

By default there is no context passed into the logger. When setting this context callable it will be called each time an request is logged with both the request and response. Letting you set context to the log entry:

$dispatcher =newDispatcher([//detect the client ip and save it in ip attribute    (newMiddlewares\ClientIP())->attribute('ip'),// Add UUID for the request so we can trace logs later in case somethings goes wrongnewMiddlewares\Uuid(),// Use the data from the other two middleware and use it as context for logging    (newMiddlewares\AccessLog($logger))        ->context(function (ServerRequestInterface$request,ResponseInterface$response) {return ['request-id' =>$request->getHeaderLine('X-Uuid'),'client-ip' =>$request->getAttribute('ip'),            ];        })]);

Custom format string

The format string tries to mimic the directives described in Apache Httpd serverdocumentation.

A custom format can be defined by placing "%" directives in the format string, which are replaced in the log file by the values as follows:

Format StringDescription
%%The percent sign.
%aClient IP address of the server request (see theipAttribute option).
%{c}aClient IP address of the server request (see theipAttribute option,differs from the original Apache directive behavior).
%ALocal IP-address.
%BSize of response in bytes, excluding HTTP headers.
%bSize of response in bytes, excluding HTTP headers. In CLF format, i.e. a- rather than a 0 when no bytes are sent.
%{VARNAME}CThe contents of cookieVARNAME in the server request sent to the server.
%DThe time taken to serve the request, in microseconds.
%{VARNAME}eThe contents of the environment variableVARNAME.
%fFilename.
%hRemote hostname. Will log the IP address ifhostnameLookups is set to false, which is the default
%HThe request protocol.
%{VARNAME}iThe contents ofVARNAME: header line(s) in the request sent to the server.
%mThe request method.
%{VARNAME}nThe contents of attributeVARNAME in the server request (differs from the original Apache directive behavior).
%{VARNAME}oThe contents ofVARNAME: header line(s) in the reply.
%pThe canonical port of the server serving the request.
%{format}pThe canonical port of the server serving the request or the string- forremote. Valid formats arecanonical,local, orremote (differs from the original Apache directive behavior).
%qThe query string (prepended with a? if a query string exists, otherwise an empty string).
%rFirst line of request.
%sStatus.
%tTime the request was received, in the format[18/Sep/2011:19:18:28 -0400]. The last number indicates the timezone offset fromGMT
%{format}tThe time, in the form given by format, which should be in an extendedstrftime(3) format (potentially localized). If the format starts withbegin: (default) the time is taken at the beginning of the request processing. If it starts withend: it is the time when the log entry gets written, close to the end of the request processing. In addition to the formats supported by strftime(3), the following format tokens are supported:sec,msec,usec (differs from the original Apache directive behavior).
%TThe time taken to serve the request, in seconds.
%{UNIT}TThe time taken to serve the request, in a time unit given by UNIT. Valid units arems for milliseconds,us for microseconds, ands for seconds. Usings gives the same result as%T without any format; usingus gives the same result as%D.
%uRemote user if the request was authenticated. May be bogus if return status (%s) is401 (unauthorized).
%UThe URL path requested, not including any query string.
%vThe host of the server request (differs from the original Apache directive behavior).
%VThe server name that appears in the server param of the request, or the request host if not available (differs from the original Apache directive behavior).
%IBytes received, including request and headers. Cannot be zero.
%OBytes sent, including headers.
%SBytes transferred (received and sent), including request and headers, cannot be zero. This is the combination of%I and%O.

The following Apache Httpd server directives are not implemented in this middleware:

Format StringDescription
%kWill print the string-.
%lWill print the string-.
%LWill print the string-.
%PWill print the string-.
%{format}PWill print the string-.
%RWill print the string-.
%XWill print the string-.
%{VARNAME}^tiWill print the string-.
%{VARNAME}^toWill print the string-.

Please seeCHANGELOG for more information about recent changes andCONTRIBUTING for contributing details.

The MIT License (MIT). Please seeLICENSE for more information.


[8]ページ先頭

©2009-2025 Movatter.jp