是否可以在 nginx 访问/错误日志中填充列?

是否可以在 nginx 访问/错误日志中填充列?

我最近在我的网站上启用了 ipv6,虽然我并不经常需要手动查看 access_log 文件,但有时我需要查看,这时我会发现我的第一个(IP)列有时长 7 个字符,有时长 39 个字符,这非常令人不舒服。

有什么方法可以将第一列填充为始终(比如说) 39 个字符宽?

我已经在 Google 上搜索并查看了 nginx 文档,但没有找到任何东西,但我想这里有人可能知道一个技巧......

我认为如果没有其他方法的话就有可能实现map,但我只知道使用正则表达式,而想不出如何处理长度或填充...

答案1

好的,自从写这篇文章以来,我已经想出了我最好的(仅读)解决方案:

map $remote_addr $padded_ip { "~^(.{39})" "$1";
                              "~^(.{38})" "$1 ";
                              "~^(.{37})" "$1  ";
                              "~^(.{36})" "$1   ";
                              "~^(.{35})" "$1    ";
                              "~^(.{34})" "$1     ";
                              "~^(.{33})" "$1      ";
                              "~^(.{32})" "$1       ";
                              "~^(.{31})" "$1        ";
                              "~^(.{30})" "$1         ";
                              "~^(.{29})" "$1          ";
                              "~^(.{28})" "$1           ";
                              "~^(.{27})" "$1            ";
                              "~^(.{26})" "$1             ";
                              "~^(.{25})" "$1              ";
                              "~^(.{24})" "$1               ";
                              "~^(.{23})" "$1                ";
                              "~^(.{22})" "$1                 ";
                              "~^(.{21})" "$1                  ";
                              "~^(.{20})" "$1                   ";
                              "~^(.{19})" "$1                    ";
                              "~^(.{18})" "$1                     ";
                              "~^(.{17})" "$1                      ";
                              "~^(.{16})" "$1                       ";
                              "~^(.{15})" "$1                        ";
                              "~^(.{14})" "$1                         ";
                              "~^(.{13})" "$1                          ";
                              "~^(.{12})" "$1                           ";
                              "~^(.{11})" "$1                            ";
                              "~^(.{10})" "$1                             ";
                              "~^(.{9})"  "$1                              ";
                              "~^(.{8})"  "$1                               ";
                              "~^(.{7})"  "$1                                "; }

是不是很漂亮?

相关内容