- Основные log файлы в Ubuntu — загрузка, авторизация, ошибки и др.
- Основные log файлы Ubuntu
- Лог загрузки
- Логи авторизации, в том числе ssh
- Логи ошибок в Ubuntu
- Cron logs
- Лог действий пользователя
- Apache Log Files
- Apache Error Log File
- Apache Access Log File
- How do I change Apache log file location?
- Linux Log Files Location And How Do I View Logs Files on Linux?
- How do I view log files on Linux?
- Common Linux log files names and usage
- Printing the Linux kernel ring buffer messages
- GUI tool to view log files on Linux
- A note about rsyslogd
- A note about systemd journal on modern Linux distros
- journalctl command examples
- See log by systemd unit or sevice
- Executable log
- Time ranges
- View log by user ID (UID) or PID
- Rverse output so that the newest entries are displayed first
- Show only Linux kernel messages
- Filter log files (grep like syntax)
- Summing up
Основные log файлы в Ubuntu — загрузка, авторизация, ошибки и др.
Приветствую читателей своего сайта. Сегодня я всесторонне рассмотрю тему тему логов в Ubuntu — ошибки, загрузка, системные логи, cron и остальное. Постараюсь дать обзорную информацию по основным моментам в этой теме. Материал в основном рассчитан на новичков, но возможно восполнит пробелы и специалистов.
Основные log файлы Ubuntu
Традиционно логи в Linux хранятся в директории /var/log . Вот описание стандартных лог файлов Ubuntu, которые там присутствуют. Кстати, если вы только планируете устанавливать ubuntu, то можете воспользоваться моей подробной статьей на этот счет — установка ubuntu server. Так же вам может быть интересен мой обзор и сравнение сервера убунту с другими linux системами — Ubuntu Server — обзор для начинающих, сравнение, отзывы.
- syslog или messages. Последнего чаще всего нет и вместо него только syslog. Это традиционные глобальные системные журналы операционной системы linux. Сюда пишутся события загрузки, ядра системы, системы инициализации systemd и т.д.
- auth.log — лог авторизации и аутентификации в системе.
- dmesg — в этом логе хранится информация о загрузке ядра и драйверов оборудования.
- alternatives.log — лог файл программы update-alternatives. Не знаю, за какие такие заслуги ей выделили отдельный лог файл, а cron, к примеру, нет.
- kern.log — лог сообщений ядра ubuntu, да и любой другой linux системы.
- maillog — сообщения почтовой системы. Обычно postfix или exim. Если на сервере ubuntu они не установлены, то и почтового лога не будет.
- dpkg.log — логирование работы пакетных менеджеров ubuntu. Обычно это apt или apt-get.
- lastlog и wtmp — информация о прошлых авторизациях пользователей.
Лог загрузки
Начнем с самого начала. В момент загрузки системы записывается вся основная информация, имеющая к ней отношение. Если у вас будут какие-то ошибки во время старта сервера, вы сможете их увидеть в этом логе. Посмотреть лог загрузки Ubuntu можно следующим образом.
У вас получится очень длинный вывод всего того, что происходило с системой на старте. Если ищите что-то конкретное, то можете сделать фильтрацию вывода с помощью grep. Допустим, вам надо узнать информацию только о диске.
Вы увидите лог загрузки системы ubuntu, содержащий информацию только о диске sda. Аналогичным образом можно фильтровать вывод по другим темам. Например, посмотреть все ошибки, которые были во время загрузки.
И так далее. Информация, которую выводит команда dmesg, хранится в log файле /var/log/dmesg .
Логи авторизации, в том числе ssh
Для того, чтобы узнать, кто и когда проходил авторизацию на сервере ubuntu, можно воспользоваться логами из файла /var/log/auth.log . Авторизация по ssh там будет выглядеть следующим образом.
Здесь мы видим ip адрес, с которого произошло подключение и слепок сертификата, так как аутентификация была произведена с его помощью. Если хотите повысить уровень логирования подключений по ssh и получать больше информации, то можете отредактировать конфигурационный файл sshd — /etc/ssh/sshd_config , добавив туда следующий параметр.
Не забудьте перезапустить службу sshd для принятия изменений:
После этого логирование подключений по ssh будет более подробное.
Лог локального входа в ubuntu тоже хранится в файле auth.log . Информация о подключении через консоль выглядит следующим образом.
Устройство /dev/tty1 говорит о том, что вход локальный.
Вы можете быстро посмотреть информацию о последних входах в систему с помощью команды last. Эта информация хранится в бинарном логе /var/log/lastlog .
Примерно то же самое можно увидеть с помощью utmpdump.
Логи ошибок в Ubuntu
Рассмотрим теперь вопрос с расположением лога ошибок в Ubuntu. Как такового отдельного error log в традиционных linux системах нет. И Убунта тут не исключение. Ошибки придется искать по системным и программным логам выборкой ключевых слов. Обычно используют следующие фразы:
- error или err
- critical или crit
- debug
- warn
Например, посмотрим в логе загрузки dmesg все сообщения уровня предупреждений (warn).
А теперь проверим ошибки в системном логе.
Видим некоторые ошибки в службе systemd-resolved.
Cron logs
Часто хочется проверить лог запуска периодических заданий cron. В Ubuntu, как мне кажется, сделали не удобно. По умолчанию, cron logs не выделены в отдельный файл. Искать их стоит в общем системном логе syslog. Например, в Centos существует отдельный лог-файл /var/log/cron, где собрана вся информация о запущенных заданиях. Предлагаю сделать так же в Ubuntu.
Для этого открываем конфигурационный файл /etc/rsyslog.d/50-default.conf и добавляем туда следующую информацию.
По умолчанию, она присутствует в конфиге, но закомментирована. Вам нужно убрать # в начале строки, чтобы раскомментировать ее. Так же я рекомендую сделать так, чтобы эти логи не дублировались в общий системный лог. Для этого немного измените следующую строку.
Я добавил в нее cron.none, чтобы логи cron не писались больше в системный лог syslog. После этого перезапустите службы rsyslog и cron и проверяйте изменения.
Теперь у нас все логи Cron в Ubuntu будут в отдельном файле.
Лог действий пользователя
Мне часто задают вопросы, как посмотреть лог действий пользователя в системе или как узнать, какие программы он запускал. По умолчанию, такие действия не логируются в ubuntu. Для этого нужно устанавливать какое-то дополнительное программное обеспечение. Я даже не знаю, кто умеет это делать. Обычно если надо фиксировать действия пользователя, включается лог работы sudo.
Для того, чтобы включить логирование действий пользователя через sudo, редактируем файл /etc/sudoers . Добавляем туда строку.
Теперь выполните какую-нибудь команду через sudo.
Выполненная команда пользователя сохранена в логе sudo.log. Теперь никто не сможет выполнить незаметно административные действия на сервере. Конечно, человек с полными правами сможет изменить любой лог файл, удалив свои действия при желании. Для этого важные логи нужно отправлять куда-то в другое место, но это уже тема отдельной статьи.
На сегодня по логам в Ubuntu у меня все. Желаю вам логов без ошибок и вечного аптайма (шутка, надо ставить обновы и перезагружаться).
Источник
Apache Log Files
Q. How do I find out Apache http server log files location? How do I change the location of Apache log file under Linux / UNIX operating system?
A. There are two type of apache httpd server log files:
Apache Error Log File
All apache errors / diagnostic information other errors found during serving requests are logged to this file. Location of error log is set using ErrorLog directive. If there is any problem, you should first take a look at this file using cat, grep or any other UNIX / Linux text utilities. This apache log file often contain details of what went wrong and how to fix it. Default error log file location:
- RHEL / Red Hat / CentOS / Fedora Linux Apache error file location – /var/log/httpd/error_log
- Debian / Ubuntu Linux Apache error log file location – /var/log/apache2/error.log
- FreeBSD Apache error log file location – /var/log/httpd-error.log
To find exact apache log file location, you can use grep command:
# grep ErrorLog /usr/local/etc/apache22/httpd.conf
# grep ErrorLog /etc/apache2/apache2.conf
# grep ErrorLog /etc/httpd/conf/httpd.conf
Sample output:
Apache Access Log File
Apache server records all incoming requests and all requests processed to a log file. The format of the access log is highly configurable. The location and content of the access log are controlled by the CustomLog directive. Default apache access log file location:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- RHEL / Red Hat / CentOS / Fedora Linux Apache access file location – /var/log/httpd/access_log
- Debian / Ubuntu Linux Apache access log file location – /var/log/apache2/access.log
- FreeBSD Apache access log file location – /var/log/httpd-access.log
To find exact apache log file location, you can use grep command:
# grep CustomLog /usr/local/etc/apache22/httpd.conf
# grep CustomLog /etc/apache2/apache2.conf
# grep CustomLog /etc/httpd/conf/httpd.conf
Sample output:
How do I change Apache log file location?
Simply edit apache configuration file and change the location. You need define new location using CustomLog or ErrorLog:
Save and close the file. Restart httpd:
# service httpd restart
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Linux Log Files Location And How Do I View Logs Files on Linux?
I am a new Linux user. I would like to know where are the log files located under Debian/Ubuntu or CentOS/RHEL/Fedora Linux server? How do I open or view log files on Linux operating systems?
Almost all logfiles are located under /var/log directory and its sub-directories on Linux. You can change to this directory using the cd command. Of course, you need to be the root user to access log files on Linux or Unix-like operating systems. You can use the following commands to see the log files which are in text format:
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Linux terminal and GUI |
Est. reading time | 4 minutes |
- less command
- more command
- cat command
- grep command
- tail command
- zcat command
- zgrep command
- zmore command
- dmesg command
- journalctl command
How do I view log files on Linux?
Open the Terminal or login as root user using ssh command. Go to /var/log directory using the following cd command:
# cd /var/log
To list files use the following ls command:
# ls
Sample outputs from RHEL 6.x server:
To view a common log file called /var/log/messages use any one of the following command:
# less /var/log/messages
# more -f /var/log/messages
# cat /var/log/messages
# tail -f /var/log/messages
# grep -i error /var/log/messages
Here is what I see:
Common Linux log files names and usage
- /var/log/messages : General message and system related stuff
- /var/log/auth.log : Authenication logs
- /var/log/kern.log : Kernel logs
- /var/log/cron.log : Crond logs (cron job)
- /var/log/maillog : Mail server logs
- /var/log/qmail/ : Qmail log directory (more files inside this directory)
- /var/log/httpd/ : Apache access and error logs directory
- /var/log/lighttpd/ : Lighttpd access and error logs directory
- /var/log/nginx/ : Nginx access and error logs directory
- /var/log/apt/ : Apt/apt-get command history and logs directory
- /var/log/boot.log : System boot log
- /var/log/mysqld.log : MySQL database server log file
- /var/log/secure or /var/log/auth.log : Authentication log
- /var/log/utmp or /var/log/wtmp : Login records file
- /var/log/yum.log or /var/log/dnf.log : Yum/Dnf command log file.
Printing the Linux kernel ring buffer messages
We use the dmesg command to examine or control the kernel ring buffer. The default action is to display all messages from the kernel ring buffer. For example:
sudo dmesg
sudo dmesg | grep ‘error’
sudo dmesg | grep -i -E ‘error|warn|failed’
sudo dmesg | more
Sample outputs:
GUI tool to view log files on Linux
System Log Viewer is a graphical, menu-driven viewer that you can use to view and monitor your system logs. This tool is only useful on your Linux powered laptop or desktop system. Most server do not have X Window system installed. You can start System Log Viewer in the following ways:
Click on System menu > Choose Administration > System Log:
Fig.01 Gnome log file viewer
Modern log viewer from Ubuntu desktop:
A note about rsyslogd
All of the above logs are generated using rsyslogd service. It is a system utility providing support for message logging. Support of both internet and unix domain sockets enables this utility to support both local and remote logging. You can view its config file by tying the following command:
# vi /etc/rsyslog.conf
# ls /etc/rsyslog.d/
In short /var/log is the location where you should find all Linux logs file. However, some applications such as httpd have a directory within /var/log/ for their own log files. You can rotate log file using logrotate software and monitor logs files using logwatch software.
A note about systemd journal on modern Linux distros
systemd-journald is a system service on modern Linux distro that comes with systemd. It collects and stores logging data. In addition, it creates and maintains structured, indexed journals based on logging information received from various sources such as Linux Kernel log messages via kmsg. Therefore, we need to use the journalctl command to query the contents of the systemd-journald.
journalctl command examples
Without any arguments, all collected logs are shown unfiltered as follows:
journalctl
View all boot messages:
journalctl -b
Want to see kernel logs from previous boot? Try:
journalctl -k -b -1
See log by systemd unit or sevice
Display a live log display from a system service apache.service or nginx.service:
journalctl -f -u apache
journalctl -f -u nginx
The -u switch can be used multiple time to save typing at the CLI. For example:
journalctl -f -u apache.service -u php-cgi.service -u mysqld.service
We can follow log in real time. Like tail -f /var/log/nginx/foo.log :
journalctl -u mysqld.service -f
journalctl -u nginx.service -f
journalctl -f
Only display last 10 log entries:
journalctl -n 10 -u nginx.service
Executable log
See all logs generated by the D-Bus or app executable
journalctl /usr/bin/dbus-daemon
journalctl /usr/local/bin/app
Time ranges
We can see logs created using time ranges. For instnace:
journalctl —since «30 min ago»
journalctl —since «1 hour ago»
journalctl —since «1 days ago»
# The date and time format is YYYY-MM-DD HH:MM:SS
# So we can do
journalctl —since «2020-06-06»
journalctl —since «2020-06-06 10:42:00»
journalctl —since «2020-06-04 10:42:00» —until «2020-06-07 10:42:00»
View log by user ID (UID) or PID
See log for user ID # 300
sudo journalctl _UID=300
View log for PID # 4242
sudo journalctl _PID=4242
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Rverse output so that the newest entries are displayed first
Try:
journalctl -r
journalctl -r -u apache.service
Show only Linux kernel messages
journalctl -k
journalctl —-dmesg
Filter log files (grep like syntax)
We can filter output to entries where the MESSAGE= field matches the specified regular expression. PERL-compatible regular expressions are used. For instance:
journalctl -k -g PATTERN
journalctl -u mysqld.service -g PATTERN
journalctl -u nginx.service -g ‘error’
journalctl -k -g failed
Click to enlarge
Summing up
You learned about various log files and showed them on Linux using CLI and GUI options. See man pages for more info using the help command or info command/man command:
man cat
man grep
man less
man more
man journalctl
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Very informative. Helped me 🙂 thumbs up
Very nice, thanks a lot
Can u help me how to redirect the /var/log/messages to email.
DNS server if any clients query log will stores /var/log/messages files i need to send those lof files in ip wise daily or weekly.
how shell i do it.
it is possible using mutt coomand and mail -s command just write a script and put in crontab it is working
I had an automatic reboot system in my server linux and I don´t find any evidence about the cause that could produce that.
Can you explain me where I have to looking for logs of error that guide me to find automatic reboot cause?.
Regards,
Gonzalo R.
your permissions. you can set it so a remote user can shut down the server. change permissions on shutdown or search your distributions forum and post if you do not find an answer in there or in google.
some distributions are setup that way by default, which is kind of annoying. Means if anyone logs in remotely in any way, they can turn you off or reboot you. NOT FUNNY. I hope you have a firewall and have it enabled.
where can i find the AT command logs. how to find out when the last time AT command run.
Use atq for last time at commands run
and check the logs
by using grep error /var/log/messages
and also check the by using atd
Thank you very much.
Chandra You can do this by opening a terminal and typing #cd /var/log/ and may view the files in the directory by typing #ls . You may view the log by typing #vi /var/log/messages .
I can see a lot of the following error in my system and I cannot understand what it means, can yu shed somelight on it
Feb 22 04:40:00 msuic3 msu6_6: ciMonitor 3 of 131 registered tasks Failed!
It’s a fruitful information…
Thanks a lot vivek
I want classify logs and store it in a database. Into what categories can/should I classify them.
Thank you,
Sparrow
Hi there Linux users, I have bean trying to in stall Debian Lenny beta 2-i386 in a raid 0 con fig, on my p/c
the hard ware is all set up for raid 0, I am having difficulty with the configuration of the partitons, boot sector, file type, the “type of file allocation table” to install. I have bean trying to track down the
var/log, but I cant find that, the location was “http://192.2.2/var/log/partman_choose_partitiion_o.png
I have bean using pure dyne live CD to help me ,but I still was not able to look at the “/var/logs,
invariable I think I need expert help. thank you in advance
this is a reply to my last message , I have given up on trying to install Linux on a virtual raid 0 system, so I ended up installing win 98 se with a new web browser OPERA and it runs like a hot dam, by far this is my most complex P/C to date, in one respect by the things it can do, the open source community has truly bean a liberator for me , not to mention Debian lenny -57-i386 1.iso I know this is old hat by computer standards , I was having problems trying to install NDISWRAPPER on an i386 architecture , and it did not help when my PC was hacked and I was effectively locked out of my p/c, no thanks to VLUG in Victoria but thats a “Hole” different story, I ended up installing ndiswrapper with a new O/S on a network complete with a bunch of other computers , I am currently working on a new black project , but that is top secret .
I have a basic account in linux of my intitue. How can i know all the login sessions done in my account ,their timing etc… an i also know any ftp or ssh done in my account.
it will tell you when, what ip address, time in and out , and for how long
Thanks. I have a question: does Linux record the software installation process? For example I use apt to install some software in Debian but I would like to know where it puts the files. Can it be found in log file?
i have smb server and i want to know the logs of each and every folder those who access please help its very urgent…..
pls go to /var/log/messages file there you will find your all logs of smb server
thanks, it helped me
how can we check online redo log file is full or empty?
Which command use to routed logs in linux
thanks, it helped me a lot. To know about log files this is very helpful…
Someone desintalled an application on my Linux server ( Control_M) – What log file should I search for that – and find out who is doing it?
Hi,
I am new to Linux, Can u pls any one of u tell me how to copy files using “rcp” from the remote location and what r da min requirements to my system.
[1] What log files in /var/logs can we safely delete to free up hard-disk space?
[2] System reports “Disk-Controller Failure” then which log files in /var/logs should we check?
or some other log files?
hi, i am having webserver in linux and mail server in windows.
in our websites we have contuct us page from that we are not able to get any email.
Can anyone help me in this reg
Let me know which linux distribution is used , and the web server having public domain ?
Dear naresh,
there is coomand –
#rsync -r Ipaddress :location of data
example :
#rsync -r192.168.0.18 :/root/slides
cite:
# cd /var/logs
# tail -f /var/log/messages
logs/log? Looks like a typo.
Trace of runtime activities in UNIX
I’ve taken a project to work upon tracing of runtime activities on unix system
into a log file. Like, to implement a program which will show the log of everything
happened in past, including many requirements, like applications i used (with the time of access),
kind of files/directories i opened, closed, created, deleted(with the time), etc.
Please suggest me something to do it in a better way.
How can i archive all the log files in redhat enterprise linux5?
Your help would be really appreciated.
Thanks
I’m confused what does the following command do :
sudo cat /var/log/messages | grep err | -d” -f5
Источник