Logwatch, настроенный для nginx с настраиваемым форматом журнала, дает пустой вывод

Проблема

Я настроил logwatch (CentOS 5.8, x64) для включения nginx, используя this в качестве руководства и используя Apache и документация nginx по форматам журналов. Проблема в том, что я использую определенный формат журнала, а именно:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" $scheme:$server_port '
                  '$status $body_bytes_sent "$http_referer" '
                  'Upstream ["$upstream_addr" ($upstream_response_time) $upstream_status : $upstream_cache_status] '
                  '"$http_user_agent" "$http_x_forwarded_for"';

(из /etc/nginx/nginx.conf )

Я перевел этот формат журнала в:

$LogFormat "%h %l %u %t \"%r\" %H:%p %>s %b \"%{Referer}i\" Upstream [\"%{Upstream-address}e\" (%{Upstream-response-time}e) %{Upstream-status}e : %{Upstream-cache-status}e] \"%{User-Agent}i\" \"%{X-Forwarded-For}e\""

для Logwatch. Изучая / usr / share / logwatch / scripts / services / http , я обнаружил, что все % {...} e , не заданное заранее, будет проигнорировано, поэтому я подумал это был бы лучший способ включить эти апстрим-переменные.

Logwatch не дает никаких результатов, учитывая nginx.

Что я сделал

Я создал следующие файлы журнала регистрации: /usr/share/logwatch/default.conf/logfiles/nginx.conf :

########################################################
#   Define log file group for nginx
# http://8bitpipe.com/?p=516
########################################################

# What actual file?  Defaults to LogPath if not absolute path....
LogFile = nginx/*access.log


# If the archives are searched, here is one or more line
# (optionally containing wildcards) that tell where they are...
#If you use a "-" in naming add that as well -mgt
Archive = nginx/archive/*access.log*

# Expand the repeats (actually just removes them now)
*ExpandRepeats

# Keep only the lines in the proper date range...
*ApplyhttpDate

/usr/share/logwatch/default.conf/services/nginx.conf :

###########################################################################
# Configuration file for nginx filter
###########################################################################

Title = "nginx"

# Which logfile group...
LogFile = nginx

# Define the log file format
#
# This is now the same as the LogFormat parameter in the configuration file
# for httpd.  Multiple instances of declared LogFormats in the httpd
# configuration file can be declared here by concatenating them with the
# '|' character.  The default, shown below, includes the Combined Log Format,
# the Common Log Format, and the default SSL log format.
#$LogFormat = "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"|%h %l %u %t \"%r\" %>s %b|%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
$LogFormat "%h %l %u %t \"%r\" %H:%p %>s %b \"%{Referer}i\" Upstream [\"%{Upstream-address}e\" (%{Upstream-response-time}e) %{Upstream-status}e : %{Upstream-cache-status}e] \"%{User-Agent}i\" \"%{X-Forwarded-For}e\""

# The following is supported for backwards compatibility, but deprecated:
# Define the log file format
#
#   the only currently supported fields are:
#                       client_ip
#                       request
#                       http_rc
#                       bytes_transfered
#                       agent
#
#$HTTP_FIELDS = "client_ip ident userid timestamp request http_rc bytes_transfered referrer agent"
#$HTTP_FORMAT = "space     space space    brace    quote   space        space       quote   quote"
# Define the field formats
#
#   the only currently supported formats are:
#                       space = space delimited field
#                       quote = quoted ("..") space delimited field
#                       brace = braced ([..]) space delimited field

# Flag to ignore 4xx and 5xx error messages as possible hack attempts
#
# Set flag to 1 to enable ignore
# or set to 0 to disable
$HTTP_IGNORE_ERROR_HACKS = 0

# Ignore requests
# Note - will not do ANY processing, counts, etc... just skip it and go to
# the next entry in the log file.
# Examples:
# 1. Ignore all URLs starting with /model/ and ending with 1 to 10 digits
#   $HTTP_IGNORE_URLS = "^/model/\d{1,10}$"
#
# 2. Ignore all URLs starting with /model/ and ending with 1 to 10 digits and
#   all URLS starting with /photographer and ending with 1 to 10 digits
#   $HTTP_IGNORE_URLS = "^/model/\d{1,10}$|^/photographer/\d{1,10}$"
#   or simply:
#   $HTTP_IGNORE_URLS = "^/(model|photographer)/\d{1,10}$"
#
# vi: shiftwidth=3 tabstop=3 et

И Я связал / usr / share / logwatch / scripts / services / http на / usr / share / logwatch / scripts / services / nginx .

Это не дает никаких ошибок при выполнении logwatch, но также не дает никаких выходных данных, хотя определенно существуют файлы журналов для анализа.

Выполнение logwatch --service nginx --print --range Все --debug 7 дает, например:

** lot of blabla about config files **

export LOGWATCH_DATE_RANGE='all'
export LOGWATCH_OUTPUT_TYPE='unformatted'
export LOGWATCH_TEMP_DIR='/var/cache/logwatch/logwatch.vdVyg9y2/'
export LOGWATCH_DEBUG='7'

Preprocessing LogFile: nginx
'/var/log/nginx/www.xxxx1.org-access.log' '/var/log/nginx/www.xxxx2.com-access.log' '/var/log/nginx/www.xxxx3.com-access.log' '/var/log/nginx/www.xxxx4.com-access.log' '/var/log/nginx/www.xxxx5.com-access.log' '/var/log/nginx/www.xxxx6.com-access.log' '/var/log/nginx/www.xxxx7.com-access.log' '/var/log/nginx/www.xxxx8.com-access.log' '/var/log/nginx/www.xxxx9.com-access.log' '/var/log/nginx/www.xxxx10.com-access.log' '/var/log/nginx/www.xxxx11.com-access.log' '/var/log/nginx/www.xxxx12-access.log' '/var/log/nginx/www.xxxx13.nu-access.log' '/var/log/nginx/www.xxxx14.org-access.log'   2>/dev/null | /usr/bin/perl /usr/share/logwatch/scripts/shared/expandrepeats ''| /usr/bin/perl /usr/share/logwatch/scripts/shared/applyhttpdate ''>/var/cache/logwatch/logwatch.vdVyg9y2/nginx

TimeFilter: Period is all

TimeFilter: SearchDate is (../.../....:..:..:..)

TimeFilter: Debug SearchDate is ( / / )
DEBUG: Inside ApplyHTTPDate...
DEBUG: Looking For: (../.../....:..:..:..)
export http_ignore_error_hacks='0'
export logformat "%h %l %u %t \"%r\" %h:%p %>s %b \"%{referer}i\" upstream [\"%{upstream-address}e\" (%{upstream-response-time}e) %{upstream-status}e : %{upstream-cache-status}e] \"%{user-agent}i\" \"%{x-forwarded-for}e\""=''

Processing Service: nginx
 ( cat /var/cache/logwatch/logwatch.vdVyg9y2/nginx  |  /usr/bin/perl /usr/share/logwatch/scripts/services/nginx) 2>&1

Почему я не получаю никаких результатов?

1
задан 14 January 2013 в 10:57
2 ответа

Я заметил, что logwatch не создает сводку журнала http/nginx, если уровень детализации низкий или 0.

Используйте

  • --detail 1 для сводки ошибочных запросов,
  • --detail 5 или --detail med для включения сводки о переданных запросах. объем данных и количество зарегистрированных роботов.
  • --detail 10 или --detail high для отображения User-Agent всех зарегистрированных роботов.

Отображать сводку nginx/http с уровнем детализации 0

Поскольку я хотел, чтобы logwatch всегда отображал полный журнал http, но не раздувал все остальные журналы, я создал отдельную копию сценария http в /etc/

sudo cp /usr/share/logwatch/scripts/services/http /etc/logwatch/scripts/services/

и изменено

my $detail = $ENV{'LOGWATCH_DETAIL_LEVEL'} || 0;

на

my $detail = 10;

в начале сценария /etc/logwatch/scripts/services/http.

Обратите внимание, что отдельный сценарий не будет получать никаких автоматических обновлений, если пакет logwatch предоставит новую версию /usr/share/logwatch/scripts/services/http.

0
ответ дан 18 April 2020 в 13:23

Я полагаю, что ваш вывод был пуст из-за *ApplyhttpDate, который использует %d/%b/%Y:%H:%M:% S: если этот шаблон не может быть найден в начале строки журнала, logwatch не передаст его в /usr/share/logwatch/scripts/services/nginx.

$SearchDate = TimeFilter('%d/%b/%Y:%H:%M:%S');

if ( $Debug > 5 ) {
   print STDERR "DEBUG: Inside ApplyHTTPDate...\n";
   print STDERR "DEBUG: Looking For: " . $SearchDate . "\n";
}

while (defined($ThisLine = <STDIN>)) {
   if ($ThisLine =~ m/\[$SearchDate/o) {
      print $ThisLine;
   }
}

SourceForge

0
ответ дан 5 August 2020 в 08:23

Теги

Похожие вопросы