> For the complete documentation index, see [llms.txt](https://bohans.gitbook.io/devops/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bohans.gitbook.io/devops/ngnix/ji-chu-zhi-shi/2.-nginx-pei-zhi/2.2-pei-zhi-zhi-ling/log_format.md).

# log\_format

<mark style="color:blue;">**log\_format**</mark>专门用于定义服务日志的格式，并且可以为格式字符串定义一个名字，以便[access\_log](/devops/ngnix/ji-chu-zhi-shi/2.-nginx-pei-zhi/2.2-pei-zhi-zhi-ling/access_log.md)指令可以直接调用。其语法格式为：

```nginx
log_format name string ...;
```

* <mark style="color:blue;">**name**</mark>：格式字符串的名字。
* <mark style="color:blue;">**string**</mark>：服务日志的格式字符串。<mark style="color:orange;">**在定义过程中，可以使用Nginx配置预设的一些变量获取相关内容，变量的名称使用双引号括起来，string整体使用单引号括起来**</mark>。

{% hint style="info" %} <mark style="color:blue;">**此指令只能在http块中进行配置**</mark>
{% endhint %}

{% hint style="success" %}
一个示例：

<pre class="language-nginx"><code class="lang-nginx"><strong>log_format  exampleLog  '$remote_addr - [$time_local] $request '
</strong>                  '$status $body_bytes_sent $http_referer '
                  '$http_user_agent';
</code></pre>

这条配置定义了服务日志文件的名称为**exampleLog**，日志输出内容如&#x4E0B;**：**

{% code overflow="wrap" %}

```log
192.168.1.102 - [31/Oct/2011:20:41:39 +0800] "GET /favicon.ico HTTP/1.1" 404 570 "-" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"
```

{% endcode %}

* $remote\_addr获取到用户机的IP地址为192.168.1.102
* $time\_local获取到本地时间为31/Oct/2011:20:41:39 +0800
* $request获取到请求为GET /favicon.ico HTTP/1.1
* $status获取到请求状态为404
* $body\_bytes\_sent获取到请求体的大小为570B
* $http\_referer未获取到任何内容
* $http\_user\_agent获取到用户使用Mozilla浏览器。
  {% endhint %}
