Error log apache2 debian

I need to find where Apache is keeping the access and error logs for a site. I have root access to a server where dozens of sites are hosted. I'm trying to debug one of those sites. When I browse ...

I need to find where Apache is keeping the access and error logs for a site.

I have root access to a server where dozens of sites are hosted. I’m trying to debug one of those sites. When I browse the site, it doesn’t show up on /var/logs/apache2/access.log or /var/logs/apache2/error.log. (The files are there, and other sites gets logged on those. In fact, there are hundreds of different log files).

Neither locate httpd.log nor find . -iname httpd.log performed at / issue any results.

The apache configuration for the site is:

ServerName REDACTED.com.br
DocumentRoot /var/www/xyz/wiki
AssignUserId xyz_wiki xyz_wiki

<Directory /var/www/xyz/wiki/data>
order allow,deny
deny from all
</Directory>
<Directory /var/www/xyz/wiki/conf>
order allow,deny
deny from all
</Directory>
<Directory /var/www/xyz/wiki/bin>
order allow,deny
deny from all
</Directory>
<Directory /var/www/xyz/wiki/inc>
order allow,deny
deny from all
</Directory>

php_admin_value open_basedir /var/www/xyz/wiki/:/mnt/vdImagem/www/xyz/wiki/

Community's user avatar

asked Feb 19, 2014 at 19:04

That Brazilian Guy's user avatar

2

You can inquire about his information from Apache’s log files but it’s generally better to inquire about these things from the actual executable. Parsing the logs can be tricky and you’ll likely make a mistake if you aren’t that familiar with how a particular setup was done on a box.

httpd -V

$ httpd -V
Server version: Apache/2.2.15 (Unix)
Server built:   Feb 13 2012 22:31:42
Server's Module Magic Number: 20051115:24
Server loaded:  APR 1.3.9, APR-Util 1.3.9
Compiled using: APR 1.3.9, APR-Util 1.3.9
Architecture:   64-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/etc/httpd"
 -D SUEXEC_BIN="/usr/sbin/suexec"
 -D DEFAULT_PIDLOG="run/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="logs/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

The key items you want to look at are as follows.

  1. This tells you the «root» directory that all the files Apache will reference start from:

     -D HTTPD_ROOT="/etc/httpd"
    
  2. config files are defined, starting here. Note that this path is relative to the path mentioned in #1, so it would be /etc/httpd/conf/httpd.conf.

     -D SERVER_CONFIG_FILE="conf/httpd.conf"
    
  3. Error log is here.

     -D DEFAULT_ERRORLOG="logs/error_log"
    

    NOTE: This one might be a bit confusing at first but on Red Hat distros there is a link that is often made in this directory, /etc/httpd called logs.

    $ ls -ld /etc/httpd/logs
    lrwxrwxrwx. 1 root root 19 Jul  9  2012 /etc/httpd/logs -> ../../var/log/httpd
    
  4. Other log files that might be utilized by Apache will be defined further in the config file, /etc/httpd/conf/httpd.conf.

answered Feb 19, 2014 at 20:22

slm's user avatar

3

I couldn’t get any of the command from the other answers to find my value. I ended up finding what i needed by running less /etc/apache2/envvars

answered Apr 15, 2021 at 15:10

Oxymoron's user avatar

OxymoronOxymoron

1611 silver badge3 bronze badges

1

Look in your apache config for the string ErrorLog.

Usually there’s one for the Apache process itself. Each VirtualHost can also define its own log files so check those as well.

If the VirtualHost doesn’t define its own log file then it will be using the one specified in the global configuration. If you think you’ve found the correct log file but you aren’t seeing the information you need then try increasing the LogLevel.

answered Feb 19, 2014 at 19:07

bahamat's user avatar

bahamatbahamat

37.5k4 gold badges70 silver badges103 bronze badges

3

I just found a file /etc/apache2/conf.d/other-vhosts-access-log which contains

# Define an access log for VirtualHosts that don't define their own logfile
CustomLog ${APACHE_LOG_DIR}/other_vhosts_access.log vhost_combined

Looks like it is a way to combine all logs from vhosts in a single file. I have checked and the accesses were being recorded there.

(source)

Inserting an ErrorLog and an AccessLog directive on the config file for that site provided me separate log files.

answered Feb 19, 2014 at 20:10

That Brazilian Guy's user avatar

Introduction

In this tutorial, you will learn everything you need to know about Apache logging to help you troubleshoot and quickly resolve any problem you may encounter on your server. Logging is a very powerful tool that will give you valuable data about all the operations of your servers. You will learn where logs are stored, how to access them, and how to customize log output to fit your needs.

Prerequisites

Apache web server.
Sudo privileges.

Step 1 — Getting To Know Apache Log Types

Apache writes logs of its events in two different log files.

Access Log — In this file, Apache stores information about incoming requests.

Error Log — This file contains information about errors that the web server encountered while processing requests.

Step 2 — Locating Apache Log Files

The location of the access log file is dependent upon the operating system on which is Apache web server running.

Location Of The Access Log

On Debian-based operating systems like Ubuntu, the access log file is located /var/log/apache2/access.log

On CentOS, the access log file is stored in /var/log/httpd/access.log
A typical access log entry might look like this:

Output:
::1 - - [13/Nov/2020:11:32:22 +0100] "GET / HTTP/1.1" 200 327 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

Enter fullscreen mode

Exit fullscreen mode

Location Of The Error Log

On Debian-based operating systems like Ubuntu, the access log file is located /var/log/apache2/error.log

On CentOS, the access log file is stored in /var/log/httpd/error.log
A typical error log entry might look like this:

Output:
[Thu May 06 12:03:28.470305 2021] [php7:error] [pid 731] [client ::1:51092] script '/var/www/html/missing.php' not found or unable to stat

Enter fullscreen mode

Exit fullscreen mode

Step 3 — Viewing Apache Logs

If you are working from an operating system with the UI, the easiest way to view stored logs is by opening files in the text editor. However, sometimes you need to view the content of the files directly in the terminal. In this case, there are few ways to do it.

You can tail command to view logs in real time:

tail -f /var/log/apache2/access.log

Enter fullscreen mode

Exit fullscreen mode

The tail command is used to print the last 10 lines from the selected file. With the -f option, the tail command will be viewing the content of the file in real-time.

To view the full content of the file, you can use the cat command:

cat /var/log/apache2/access.log

Enter fullscreen mode

Exit fullscreen mode

You may also want to find a specific term in the file. In that case, you can use the grep command:

grep GET /var/log/apache2/access.log

Enter fullscreen mode

Exit fullscreen mode

First, specify the term you want to search for, then specify the actual log file. In this case, we are looking for lines in the access log file where GET therm is present.

Step 4 — Configuring Apache Access Logs

In the access log, you can see what pages are users visiting, the status of their requests, and how long it took to process their requests.

Log Formats

As was mentioned earlier, logs are a powerful tool. To be able to use this tool you need to understand the format in which are logs stored. The format of the access logs and the log file location is defined in the CustomLog directive. This directive can be used in the server configuration file (/etc/apache2/apache2.conf) or your virtual host entry. Be aware that defining the same CustomLog directive in both files may cause problems.

Common Log Format

The common log format is the standardized text file format used by many web servers. It’s popular as it is easy to read and contains just the necessary information. Its defined in the /etc/apache2/apache2.conf configuration file and its format look like this:

LogFormat "%h %l %u %t \"%r\" %>s %O" common

Enter fullscreen mode

Exit fullscreen mode

The entry in the log file will look like this:

Output:
127.0.0.1 alice Alice [06/May/2021:11:26:42 +0200] "GET / HTTP/1.1" 200 3477
This is the information that the log message contains:

Enter fullscreen mode

Exit fullscreen mode

%h — 127.0.0.1 — Hostname or IP address of the client that made the request
%l — alice — Remote log name (Name used to log in a user). If not set, the default value will be used —
%u — Alice — Remote username (Username of logged-in user). If not set, the default value will be used —
%t — [06/May/2021:11:26:42 +0200] — Day and time of the request
«%r» — «GET / HTTP/1.1» — Actual request
%>s — 200 — Response code
%O — 3477 — Size of the response in bytes

Combined Log Format

The combined log format is very similar to the common log format but contains few extra pieces of information.

Its defined in the /etc/apache2/apache2.conf configuration file and its format look like this:

LogFormat «%h %l %u %t «%r» %>s %O «%{Referer}i» «%{User-Agent}i»» combined
The entry in the log file will look like this:

Output:
127.0.0.1 alice Alice [06/May/2021:11:18:36 +0200] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"

Enter fullscreen mode

Exit fullscreen mode

These are the extra pieces of information (aside from those present in the common format):

«%{Referer}i» — «-» — URL of the referer
«%{User-Agent}i» — «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36» — Detailed information about he browser of the user that made the request.

Custom Log Format

You can define your custom log format in the /etc/apache2/apache2.conf using LogFormat directive followed by the actual format of the output and nickname that will be used as format identifier.

For this example, we will create a custom log format named custom that will only print the user’s browser information. The format will look like this:

LogFormat "%{User-agent}i" custom

Enter fullscreen mode

Exit fullscreen mode

In the virtual host file, we will use the CustomLog directive to set the format of the log messages to the custom and log file to the default access log.

CustomLog ${APACHE_LOG_DIR}/access.log custom

Enter fullscreen mode

Exit fullscreen mode

Now, we make a request and the Apache server will log the information about the browser that made the request into the access.log file. The log message will look like this:

Output:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36

Enter fullscreen mode

Exit fullscreen mode

Logging Into Multiple Files
You can also write multiple messages into multiple files. This can be done by using the CustomLog directive more than once. Note that when logging into the custom log file, the log file has to be manually created before you can log into it.

CustomLog ${APACHE_LOG_DIR}/custom.log custom
CustomLog ${APACHE_LOG_DIR}/access.log common

Enter fullscreen mode

Exit fullscreen mode

Step 5 — Configuring Apache Error Logs

The error log contains information about the errors the web server encountered while processing the request. A common error while processing the request is a request for a missing file.

You can choose to which file the error messages will be stored using the ErrorLog directive in your virtual host configuration file. This directive takes one argument — path to the log file. Here is an example from default virtual host configuration file /etc/apache2/sites-available/000-default.conf

ErrorLog ${APACHE_LOG_DIR}/error.log

Enter fullscreen mode

Exit fullscreen mode

You can choose a custom file but be aware as the file has to be manually created before you can log into it.

In the virtual host configuration file, you can also specify the level of errors that will be logged using the LogLevel directive. Setting this option to a specific value, the server will ignore errors with lover severity then set in the LogLevel directive. It is not recommended to change it to higher values than error.

These are the possible values:

trace1 — trace8 — Trace messages (LOWEST)
debug — messages used for debugging
info — informational messages
notice — notices
warn — warnings
error — errors while processing the request (doesn’t require immediate action)
crit — Critical error that requires prompt action
alert — Error that requires immediate action
emerg — System is unusable
You can set the log level using the LogLevel directive like this:

LogLevel info

Enter fullscreen mode

Exit fullscreen mode

If the log level is not set, the server will set the log level to warn by default.

Conclusion

In this tutorial, you learned what types of log Apache web server stores, where you can find those logs, how to understand the formatting, and how to create your custom log formats. Now, you can log into multiple files and set the level of errors to which the server will react. At this point, you know everything you need to efficiently debug your web application.

You can explore more on linux logging in logtail tutorial library.

8 сентября, 2020 11:28 дп
4 069 views
| Комментариев нет

Centos, Debian, LAMP Stack, Ubuntu

Эта серия мануалов поможет вам предотвратить или устранить самые распространенные ошибки, которые возникают при работе с веб-сервером Apache.

Каждый последующий мануал в этой серии включает описание распространенных ошибок Apache, связанных с конфигурацией, сетью, файловой системой или привилегиями. Мы начнем с обзора команд и логов, которые вы можете использовать для устранения неполадок Apache. В последующих руководствах мы подробно рассмотрим конкретные ошибки.

Есть три основные команды и несколько общих логов, которые вы можете использовать, чтобы начать устранение ошибок Apache. По сути здесь вы найдете стандартную стратегию поиска ошибок и их причин: обычно эти команды используются в указанном здесь порядке, после чего можно изучить логи на предмет конкретных диагностических данных.

Команды, которые необходимы для устранения неполадок Apache в большинстве дистрибутивов Linux:

  • systemctl – используется для управления сервисами Linux и взаимодействия с ними через менеджер сервисов systemd.
  • journalctl – используется для запроса и просмотра логов, созданных systemd.
  • apachectl – при устранении неполадок эта команда используется для проверки конфигурации Apache.

Далее мы подробно опишем эти команды, способы их использования и расположение логов Apache, в которых можно найти дополнительную информацию об ошибках.

Примечание: В системах Debian и Ubuntu сервис и процесс Apache называется apache2, а в CentOS, Fedora и других системах RedHat – httpd. Имя сервиса и процесса – это единственное отличие команд запуска, остановки и проверки состояния Apache в разных системах. Логи journalctl также должны работать одинаково в любой системе Linux, которая использует systemd для управления Apache. При работе с этим мануалом вы должны использовать правильное имя сервиса в зависимости от вашего дистрибутива Linux.

Команды systemctl для Apache

Чтобы устранить распространенные ошибки Apache с помощью менеджера сервисов systemd, первым делом вам необходимо проверить состояние процессов Apache в вашей системе. Следующие команды systemctl помогут вам узнать больше о состоянии процессов Apache.

В Ubuntu и Debian используйте:

sudo systemctl status apache2.service -l --no-pager

Флаг -l отображает полный вывод без сокращения. Флаг –no-pager направляет вывод непосредственно на ваш терминал. Вы должны получить такой результат:

apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: active (running) since Mon 2020-07-13 14:43:35 UTC; 1 day 4h ago
Process: 929 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
Main PID: 1346 (apache2)
Tasks: 55 (limit: 4702)
CGroup: /system.slice/apache2.service
├─1346 /usr/sbin/apache2 -k start
. . .

Чтобы изучить процесс веб-сервера в CentOS и Fedora, используйте:

sudo systemctl status httpd.service -l --no-pager

Вы получите такой результат:

httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: active (running) since Tue 2020-07-14 19:46:52 UTC; 3s ago
Docs: man:httpd.service(8)
Main PID: 21217 (httpd)
Status: "Started, listening on: port 80"
Tasks: 213 (limit: 2881)
Memory: 16.6M
CGroup: /system.slice/httpd.service
├─21217 /usr/sbin/httpd -DFOREGROUND
. . .
Jul 14 19:46:52 localhost.localdomain httpd[21217]: Server configured, listening on: port 80

Независимо от дистрибутива вы должны обратить внимание на строку Active в выводе. Если ваш сервер Apache не отображается как active (running), хотя он должен работать, возможно, произошла ошибка и прервала его работу. Как правило, при возникновении ошибок в выводе будет строка failed:

Active: failed (Result: exit-code) since Tue 2020-07-14 20:01:29 UTC; 1s ago

Если проблема заключается в процессе или конфигурации Apache, вы можете устранить ее с помощью команды journalctl.

Команды journalctl для Apache

Чтобы проверить логи systemd для Apache, вы можете использовать команду journalctl. Логи systemd для Apache обычно содержат данные о проблемах с запуском или управлением процессом Apache.

Эти логи отделены от логов запросов и ошибок Apache. Команда journalctl отображает логи systemd, которые описывают сам сервис Apache (от его запуска до завершения работы, включая все ошибки процесса, которые могут возникнуть на этом пути).

В системах Ubuntu и Debian для проверки логов используйте следующую команду:

sudo journalctl -u apache2.service --since today --no-pager

Флаг –since today ограничивает вывод команды записями лога, начиная с 00:00:00 текущего дня. Использование этой опции поможет ограничить объем записей лога, которые вам необходимо изучить для выявления ошибок. Вы должны получить следующий результат:

Jul 14 20:12:14 ubuntu2004 systemd[1]: Starting The Apache HTTP Server...
Jul 14 20:12:14 ubuntu2004 systemd[1]: Started The Apache HTTP Server.

Если вы используете систему на базе CentOS или Fedora, введите эту версию команды:

sudo journalctl -u httpd.service --since today --no-pager

Вы получите такой результат:

Jul 14 20:13:09 centos8 systemd[1]: Starting The Apache HTTP Server...
. . .
Jul 14 20:13:10 centos8 httpd[21591]: Server configured, listening on: port 80

В случае ошибки в выводе будет строка, приведенная ниже (имя хоста будет отличаться в зависимости от дистрибутива Linux):

Jul 14 20:13:37 yourhostname systemd[1]: Failed to start The Apache HTTP Server.

Если в ваших логах Apache есть подобные ошибки, то следующее, что нужно сделать для устранения возможных проблем – это исследовать конфигурации Apache с помощью инструмента командной строки apachectl.

Устранение неполадок с помощью apachectl

Большинство дистрибутивов Linux включают утилиту apachectl в установку Apache по умолчанию. apachectl – бесценный инструмент, помогающий обнаруживать и диагностировать проблемы конфигурации Apache.

Проверьте конфигурацию Apache с помощью команды apachectl configtest. Инструмент проанализирует ваши файлы Apache и обнаружит все ошибки или недостающие настройки перед попыткой запуска сервера.

Команда одинакова для дистрибутивов Ubuntu, Debian, CentOS и Fedora:

sudo apachectl configtest

Если конфигурация Apache не содержит ошибок, вы получите такой результат:

Syntax OK

В зависимости от вашего дистрибутива Linux в выводе могут быть и другие строки, но самая важная строка – это та, в которой говорится, что с синтаксисом все ок.

Если в вашей конфигурации Apache есть ошибка (например, директива ссылается на деактивированный модуль) или опечатка, apachectl обнаружит ее и попытается уведомить вас о проблеме.

Например, попытка использовать в директиве отключенный модуль Apache приведет к появлению следующих сообщений apachectl:

AH00526: Syntax error on line 232 of /etc/apache2/apache2.conf:
Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.

В этом примере модуль ssl не включен, поэтому при проверке конфигурации директива SSLEngine выдает ошибку. Последняя строка также указывает, что в логе ошибок Apache может содержаться дополнительная информация, и это следующее место для поиска подробной отладочной информации.

Логи Apache

Логи Apache – очень полезный ресурс для устранения неполадок. Как правило, каждая ошибка, возникающая в браузере или другом HTTP-клиенте, создает соответствующую запись в логах Apache. Иногда Apache также выводит в свои логи ошибки, связанные с конфигурацией, встроенными модулями и другой отладочной информацией.

Чтобы проверить ошибки при устранении неполадок Apache на сервере Fedora, CentOS или RedHat, изучите файл /var/log/httpd/error_log.

Если вы устраняете неполадки в системе Debian или Ubuntu, проверьте /var/log/apache2/error.log с помощью инструмента tail или less. Например, чтобы просмотреть последние две строки лога ошибок с помощью tail, выполните следующую команду:

sudo tail -n 2 /var/log/apache2/error.log

Замените количество строк, которые вы хотите изучить. Укажите количество строк вместо числа 2 в команде.

В системе CentOS или Fedora файл журнала для проверки – /var/log/httpd/error_log.

Ниже мы приводим пример пример ошибки (ее текст не зависит от дистрибутива Linux):

[Wed Jul 15 01:34:12.093005 2020] [proxy:error] [pid 13949:tid 140150453516032] (13)Permission denied: AH00957: HTTP: attempt to connect to 127.0.0.1:9090 (127.0.0.1) failed
[Wed Jul 15 01:34:12.093078 2020] [proxy_http:error] [pid 13949:tid 140150453516032] [client 127.0.0.1:42480] AH01114: HTTP: failed to make connection to backend: 127.0.0.1

Эти две строки представляют собой отдельные сообщения об ошибках. Обе они ссылаются на модуль, вызвавший ошибку (proxy в первой строке, proxy_http во второй), и содержат код ошибки, индивидуальный для модуля. Первый, AH00957, указывает на то, что сервер Apache пытался подключиться к бэкенд-серверу (в данном случае к 127.0.0.1 по порту 9090) с помощью модуля proxy, но не смог этого сделать.

Вторая ошибка исходит из первой: AH01114 – это ошибка модуля proxy_http, которая также указывает на то, что Apache не смог подключиться к бэкенд-серверу для выполнения HTTP-запроса.

Эти строки мы привели просто для примера. Если вы диагностируете ошибки на своем сервере Apache, скорее всего, вы найдете совсем другие строки с ошибками в ваших логах. Независимо от дистрибутива Linux, строки ошибок в логах всегда содержат соответствующий модуль Apache и код ошибки, а также текстовое описание ошибки.

Как только вы поймете, что могло вызвать вызывать проблему на вашем сервере Apache, вы можете продолжить исследование и устранение неполадок. Код ошибки и текстовое описание особенно полезны, поскольку дают конкретные указания, которые можно использовать для сужения диапазона возможных причин возникновения ошибки.

Заключение

Устранение ошибок Apache может включать как диагностику ошибок сервиса, так и обнаружение неверно настроенных параметров модулей. В этом вводном руководстве по диагностике Apache мы посмотрели, как использовать ряд утилит, чтобы сузить круг возможных причин появления ошибок. Обычно эти утилиты нужно использовать в том же порядке, в каком они описаны тут (но вы всегда можете пропустить некоторые действия или начать сразу с изучения логов, если у вас есть общее представление о том, в чем может быть проблема).

Однако чаще всего полезно следовать общей схеме устранения неполадок и использовать эти инструменты в описанном порядке. Начните с systemctl, чтобы проверить состояние сервера Apache. Если вам нужна дополнительная информация, изучите логи systemd для Apache с помощью команды journalctl. Если после проверки journalctl проблема все еще не ясна, проверьте конфигурации Apache с помощью команды apachectl configtest. Для более глубокого изучения неполадок проверьте логи Apache, обычно они указывают на конкретную ошибку (предоставляя полезные для диагностики данные и коды ошибок).

Tags: Apache, apachectl, journalctl, systemctl

Понравилась статья? Поделить с друзьями:
  • Error log apache где находится
  • Error log apache linux
  • Error loco translate failed to start up
  • Error locking project file
  • Error loadlibrary failed with error 1114 как исправить