PHPackages                             middlewares/access-log - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. middlewares/access-log

ActiveLibrary[HTTP &amp; Networking](/categories/http)

middlewares/access-log
======================

Middleware to generate access logs

v2.2.0(1y ago)20121.2k↑17.2%82MITPHPPHP ^7.2 || ^8.0CI passing

Since Oct 9Pushed 1y ago2 watchersCompare

[ Source](https://github.com/middlewares/access-log)[ Packagist](https://packagist.org/packages/middlewares/access-log)[ Docs](https://github.com/middlewares/access-log)[ RSS](/packages/middlewares-access-log/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (21)Used By (2)

middlewares/access-log
======================

[](#middlewaresaccess-log)

[![Latest Version on Packagist](https://camo.githubusercontent.com/8a183685b2c3044155e97fc1a8d223a9b9f62afd4792d7f5ae7604bbd79b1ee4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6964646c6577617265732f6163636573732d6c6f672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/middlewares/access-log)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Testing](https://github.com/middlewares/access-log/workflows/testing/badge.svg)](https://github.com/middlewares/access-log/workflows/testing/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/af7528a9b269513b045a6de8300f0089f5d0d7c3254a5040757e859db989a648/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6964646c6577617265732f6163636573732d6c6f672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/middlewares/access-log)

Middleware to generate access logs for each request using the [Apache's access log format](https://httpd.apache.org/docs/2.4/logs.html#accesslog). This middleware requires a [Psr log implementation](https://packagist.org/providers/psr/log-implementation), for example [monolog](https://github.com/Seldaek/monolog).

Requirements
------------

[](#requirements)

- PHP &gt;= 7.2
- A [PSR-7 http library](https://github.com/middlewares/awesome-psr15-middlewares#psr-7-implementations)
- A [PSR-15 middleware dispatcher](https://github.com/middlewares/awesome-psr15-middlewares#dispatcher)
- A [PSR-3 logger](https://packagist.org/search/?tags=psr-3)

Installation
------------

[](#installation)

This package is installable and autoloadable via Composer as [middlewares/access-log](https://packagist.org/packages/middlewares/access-log).

```
composer require middlewares/access-log
```

Example
-------

[](#example)

```
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

//Create the logger
$logger = new Logger('access');
$logger->pushHandler(new StreamHandler(fopen('/access-log.txt', 'r+')));

$dispatcher = new Dispatcher([
    new Middlewares\AccessLog($logger)
]);

$response = $dispatcher->dispatch(new ServerRequest());
```

Usage
-----

[](#usage)

This middleware uses [PSR-3](http://www.php-fig.org/psr/psr-3/) logger standard to store the logs, so you need to pass a `Psr\Log\LoggerInterface` instance to the constructor.

### format

[](#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](#custom-format-string)) 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`

```
use Middlewares\AccessLog;

$format = AccessLog::FORMAT_COMMON_VHOST;

$accessLog = (new AccessLog($logger))->format($format);
```

### ipAttribute

[](#ipattribute)

By default uses the `REMOTE_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 example [client-ip](https://github.com/middlewares/client-ip):

```
Dispatcher::run([
    //detect the client ip and save it in "ip" attribute
    (new Middlewares\ClientIP())->attribute('ip'),

    //use that attribute
    (new Middlewares\AccessLog($logger))->ipAttribute('ip')
]);
```

### hostnameLookups

[](#hostnamelookups)

Enable the `hostnameLookups` flag used to get the remote hostname (`%h`). By default is `false`.

### context

[](#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 = new Dispatcher([
    //detect the client ip and save it in ip attribute
    (new Middlewares\ClientIP())->attribute('ip'),

    // Add UUID for the request so we can trace logs later in case somethings goes wrong
    new Middlewares\Uuid(),

    // Use the data from the other two middleware and use it as context for logging
    (new Middlewares\AccessLog($logger))
        ->context(function (ServerRequestInterface $request, ResponseInterface $response) {
            return [
                'request-id' => $request->getHeaderLine('X-Uuid'),
                'client-ip' => $request->getAttribute('ip'),
            ];
        })
]);
```

Custom format string
--------------------

[](#custom-format-string)

The format string tries to mimic the directives described in Apache Httpd server [documentation](http://httpd.apache.org/docs/2.4/mod/mod_log_config.html).

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.`%a`Client IP address of the server request (see the `ipAttribute` option).`%{c}a`Client IP address of the server request (see the `ipAttribute` option, *differs from the original Apache directive behavior*).`%A`Local IP-address.`%B`Size of response in bytes, excluding HTTP headers.`%b`Size of response in bytes, excluding HTTP headers. In CLF format, i.e. a `-` rather than a 0 when no bytes are sent.`%{VARNAME}C`The contents of cookie `VARNAME` in the server request sent to the server.`%D`The time taken to serve the request, in microseconds.`%{VARNAME}e`The contents of the environment variable `VARNAME`.`%f`Filename.`%h`Remote hostname. Will log the IP address if `hostnameLookups` is set to false, which is the default`%H`The request protocol.`%{VARNAME}i`The contents of `VARNAME:` header line(s) in the request sent to the server.`%m`The request method.`%{VARNAME}n`The contents of attribute `VARNAME` in the server request (*differs from the original Apache directive behavior*).`%{VARNAME}o`The contents of `VARNAME:` header line(s) in the reply.`%p`The canonical port of the server serving the request.`%{format}p`The canonical port of the server serving the request or the string `-` for `remote`. Valid formats are `canonical`, `local`, or `remote` (*differs from the original Apache directive behavior*).`%q`The query string (prepended with a `?` if a query string exists, otherwise an empty string).`%r`First line of request.`%s`Status.`%t`Time the request was received, in the format `[18/Sep/2011:19:18:28 -0400]`. The last number indicates the timezone offset from `GMT``%{format}t`The time, in the form given by format, which should be in an extended `strftime(3)` format (potentially localized). If the format starts with `begin:` (default) the time is taken at the beginning of the request processing. If it starts with `end:` 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*).`%T`The time taken to serve the request, in seconds.`%{UNIT}T`The time taken to serve the request, in a time unit given by UNIT. Valid units are `ms` for milliseconds, `us` for microseconds, and `s` for seconds. Using `s` gives the same result as `%T` without any format; using `us` gives the same result as `%D`.`%u`Remote user if the request was authenticated. May be bogus if return status (`%s`) is `401` (unauthorized).`%U`The URL path requested, not including any query string.`%v`The host of the server request (*differs from the original Apache directive behavior*).`%V`The 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*).`%I`Bytes received, including request and headers. Cannot be zero.`%O`Bytes sent, including headers.`%S`Bytes 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`%k`Will print the string `-`.`%l`Will print the string `-`.`%L`Will print the string `-`.`%P`Will print the string `-`.`%{format}P`Will print the string `-`.`%R`Will print the string `-`.`%X`Will print the string `-`.`%{VARNAME}^ti`Will print the string `-`.`%{VARNAME}^to`Will print the string `-`.---

Please see [CHANGELOG](CHANGELOG.md) for more information about recent changes and [CONTRIBUTING](CONTRIBUTING.md) for contributing details.

The MIT License (MIT). Please see [LICENSE](LICENSE) for more information.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance45

Moderate activity, may be stable

Popularity42

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 79.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~162 days

Recently: every ~393 days

Total

20

Last Release

422d ago

Major Versions

v0.10.0 → v1.0.02018-01-27

v1.2.0 → v2.0.02020-12-02

PHP version history (3 changes)v0.1.0PHP ^5.6 || ^7.0

v0.10.0PHP ^7.0

v2.0.0PHP ^7.2 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/e99df56b617f4af8cf0556a51a0ca20c7420104920c57d7e9eab093f92bb744f?d=identicon)[oscarotero](/maintainers/oscarotero)

![](https://www.gravatar.com/avatar/42e0d72f42eb7d84f67e20d28606da42e5a3248ca908b1eadb4366aafeae2561?d=identicon)[filisko](/maintainers/filisko)

---

Top Contributors

[![oscarotero](https://avatars.githubusercontent.com/u/377873?v=4)](https://github.com/oscarotero "oscarotero (94 commits)")[![ajgarlag](https://avatars.githubusercontent.com/u/388184?v=4)](https://github.com/ajgarlag "ajgarlag (12 commits)")[![WyriHaximus](https://avatars.githubusercontent.com/u/147145?v=4)](https://github.com/WyriHaximus "WyriHaximus (6 commits)")[![filisko](https://avatars.githubusercontent.com/u/8798694?v=4)](https://github.com/filisko "filisko (2 commits)")[![reisraff](https://avatars.githubusercontent.com/u/4624214?v=4)](https://github.com/reisraff "reisraff (2 commits)")[![lcobucci](https://avatars.githubusercontent.com/u/201963?v=4)](https://github.com/lcobucci "lcobucci (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")

---

Tags

access-logshttploggingmiddlewarepsr-15httppsr-7middlewareloggingserveraccesspsr-15logger

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/middlewares-access-log/health.svg)

```
[![Health](https://phpackages.com/badges/middlewares-access-log/health.svg)](https://phpackages.com/packages/middlewares-access-log)
```

###  Alternatives

[middlewares/request-handler

Middleware to execute request handlers

451.6M26](/packages/middlewares-request-handler)[middlewares/fast-route

Middleware to use FastRoute

96191.1k15](/packages/middlewares-fast-route)[middlewares/negotiation

Middleware to implement content negotiation

47442.1k11](/packages/middlewares-negotiation)[middlewares/payload

Middleware to parse the body of the request with support for json, csv and url-encode

32466.8k17](/packages/middlewares-payload)[middlewares/http-authentication

Middleware to implement Basic and Digest Http authentication

35302.0k2](/packages/middlewares-http-authentication)[middlewares/client-ip

Middleware to detect the client ip and save it as a request attribute

16629.7k9](/packages/middlewares-client-ip)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
