- 4 Ways to Watch or Monitor Log Files in Real Time
- 1. tail Command – Monitor Logs in Real Time
- 2. Multitail Command – Monitor Multiple Log Files in Real Time
- 3. lnav Command – Monitor Multiple Log Files in Real Time
- 4. less Command – Display Real Time Output of Log Files
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Лог файлы Linux по порядку
- Основные лог файлы
- И другие журналы
- Чем просматривать — lnav
- What are Linux Logs? How to View Them, Most Important Directories, and More
- A Definition of Linux Logs
- How to View Linux Logs
- Most Important Linux Logs
4 Ways to Watch or Monitor Log Files in Real Time
How can I see the content of a log file in real time in Linux? Well there are a lot of utilities out there that can help a user to output the content of a file while the file is changing or continuously updating. Some of the most known and heavily used utility to display a file content in real time in Linux is the tail command (manage files effectively).
1. tail Command – Monitor Logs in Real Time
As said, tail command is the most common solution to display a log file in real time. However, the command to display the file has two versions, as illustrated in the below examples.
In the first example the command tail needs the -f argument to follow the content of a file.
Monitor Apache Logs in Real Time
The second version of the command is actually a command itself: tailf. You won’t need to use the -f switch because the command is built-in with the -f argument.
Real Time Apache Logs Monitoring
Usually, the log files are rotated frequently on a Linux server by the logrotate utility. To watch log files that get rotated on a daily base you can use the -F flag to tail command.
The tail -F will keep track if new log file being created and will start following the new file instead of the old file.
However, by default, tail command will display the last 10 lines of a file. For instance, if you want to watch in real time only the last two lines of the log file, use the -n file combined with the -f flag, as shown in the below example.
Watch Last Two Lines of Logs
2. Multitail Command – Monitor Multiple Log Files in Real Time
Another interesting command to display log files in real time is multitail command. The name of the command implies that multitail utility can monitor and keep track of multiple files in real time. Multitail also lets you navigate back and forth in the monitored file.
To install mulitail utility in Debian and RedHat based systems issue the below command.
To display the output of two log file simultaneous, execute the command as shown in the below example.
Multitail Monitor Logs
3. lnav Command – Monitor Multiple Log Files in Real Time
Another interesting command, similar to multitail command is the lnav command. Lnav utility can also watch and follow multiple files and display their content in real time.
To install lnav utility in Debian and RedHat based Linux distributions by issuing the below command.
Watch the content of two log files simultaneously by issuing the command as shown in the below example.
lnav – Real Time Logs Monitoring
4. less Command – Display Real Time Output of Log Files
Finally, you can display the live output of a file with less command if you type Shift+F .
As with tail utility, pressing Shift+F in a opened file in less will start following the end of the file. Alternatively, you can also start less with less +F flag to enter to live watching of the file.
Watch Logs Using Less Command
That’s It! You may read these following articles on Log monitoring and management.
In this article, we showed how to watch data being appended in log files in real-time on the terminal in Linux. You can ask any questions or share your thoughts concerning this guide via the comment form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Лог файлы Linux по порядку
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе Linux, который никогда не читал лог файлы. Операционная система и работающие приложения постоянно создают различные типы сообщений, которые регистрируются в различных файлах журналов. Умение определить нужный файл журнала и что искать в нем поможет существенно сэкономить время и быстрее устранить ошибку.
Журналирование является основным источником информации о работе системы и ее ошибках. В этом кратком руководстве рассмотрим основные аспекты журналирования операционной системы, структуру каталогов, программы для чтения и обзора логов.
Основные лог файлы
Все файлы журналов, можно отнести к одной из следующих категорий:
Большинство же лог файлов содержится в директории /var/log .
- /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
- /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
- /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ —level= можно отфильтровать вывод по критерию значимости.
- /var/log/alternatives.log — Вывод программы update-alternatives , в котором находятся символические ссылки на команды или библиотеки по умолчанию.
- /var/log/anaconda.log — Записи, зарегистрированные во время установки системы.
- /var/log/audit — Записи, созданные службой аудита auditd .
- /var/log/boot.log — Информация, которая пишется при загрузке операционной системы.
- /var/log/cron — Отчет службы crond об исполняемых командах и сообщения от самих команд.
- /var/log/cups — Все, что связано с печатью и принтерами.
- /var/log/faillog — Неудачные попытки входа в систему. Очень полезно при проверке угроз в системе безопасности, хакерских атаках, попыток взлома методом перебора. Прочитать содержимое можно с помощью команды faillog .
- var/log/kern.log — Журнал содержит сообщения от ядра и предупреждения, которые могут быть полезны при устранении ошибок пользовательских модулей встроенных в ядро.
- /var/log/maillog/ или /var/log/mail.log — Журнал почтового сервера, используемого на ОС.
- /var/log/pm-powersave.log — Сообщения службы экономии заряда батареи.
- /var/log/samba/ — Логи файлового сервера Samba , который используется для доступа к общим папкам Windows и предоставления доступа пользователям Windows к общим папкам Linux.
- /var/log/spooler — Для представителей старой школы, содержит сообщения USENET. Чаще всего бывает пустым и заброшенным.
- /var/log/Xorg.0.log — Логи X сервера. Чаще всего бесполезны, но если в них есть строки начинающиеся с EE, то следует обратить на них внимание.
Для каждого дистрибутива будет отдельный журнал менеджера пакетов.
- /var/log/yum.log — Для программ установленных с помощью Yum в RedHat Linux.
- /var/log/emerge.log — Для ebuild -ов установленных из Portage с помощью emerge в Gentoo Linux.
- /var/log/dpkg.log — Для программ установленных с помощью dpkg в Debian Linux и всем семействе родственных дистрибутивах.
И немного бинарных журналов учета пользовательских сессий.
- /var/log/lastlog — Последняя сессия пользователей. Прочитать можно командой last .
- /var/log/tallylog — Аудит неудачных попыток входа в систему. Вывод на экран с помощью утилиты pam_tally2 .
- /var/log/btmp — Еже один журнал записи неудачных попыток входа в систему. Просто так, на всякий случай, если вы еще не догадались где следует искать следы активности взломщиков.
- /var/log/utmp — Список входов пользователей в систему на данный момент.
- /var/log/wtmp — Еще один журнал записи входа пользователей в систему. Вывод на экран командой utmpdump .
И другие журналы
Так как операционная система, даже такая замечательная как Linux, сама по себе никакой ощутимой пользы не несет в себе, то скорее всего на сервере или рабочей станции будет крутится база данных, веб сервер, разнообразные приложения. Каждое приложения или служба может иметь свой собственный файл или каталог журналов событий и ошибок. Всех их естественно невозможно перечислить, лишь некоторые.
- /var/log/mysql/ — Лог базы данных MySQL.
- /var/log/httpd/ или /var/log/apache2/ — Лог веб сервера Apache, журнал доступа находится в access_log , а ошибки — в error_log .
- /var/log/lighthttpd/ — Лог веб сервера lighttpd.
В домашнем каталоге пользователя могут находится журналы графических приложений, DE.
/.xsession-errors — Вывод stderr графических приложений X11.
/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.
Чем просматривать — lnav
Почти все знают об утилите less и команде tail -f . Также для этих целей сгодится редактор vim и файловый менеджер Midnight Commander. У всех есть свои недостатки: less неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью .
Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.
Установка пакета как обычно одной командой.
Навигатор журналов lnav понимает ряд форматов файлов.
- Access_log веб сервера.
- CUPS page_log
- Syslog
- glog
- dpkg.log
- strace
- Произвольные записи с временными отметками
- gzip, bzip
- Журнал VMWare ESXi/vCenter
Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.
Программа умеет напрямую открывать архивный файл.
Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу . Это с моего syslog-а.
Кроме этого поддерживается подсветка синтаксиса, дополнение по табу и разные полезности в статусной строке. К недостаткам можно отнести нестабильность поведения и зависания. Надеюсь lnav будет активно развиваться, очень полезная программа на мой взгляд.
Источник
What are Linux Logs? How to View Them, Most Important Directories, and More
Logging is a must for today’s developers; that’s why we built Retrace with a built-in, centralized log management tool to enable you to collect all your log data in one place for streamlined monitoring and better insights. Retrace works out-of-the-box with your stack, including Linux, Azure, MySQL, Windows, AWS, Oracle, MongoDB, and more. And, it includes all the features you need in a log management tool (log tailing, full-text searching, structured logging, monitoring and alerting, etc.), plus it’s integrated with error tracking for a seamless experience.
While we’ve built Retrace to do the hard work for you, it’s still important to understand Linux logs, how to view them, and which logs are most important to your work. We wrote this mini-guide to give you all the need-to-know essentials in an easily digestible format. (It won’t take up your entire lunch break – promise!)
A Definition of Linux Logs
Linux logs provide a timeline of events for the Linux operating system, applications, and system, and are a valuable troubleshooting tool when you encounter issues. Essentially, analyzing log files is the first thing an administrator needs to do when an issue is discovered.
For desktop app-specific issues, log files are written to different locations. For example, Chrome writes crash reports to ‘
/.chrome/Crash Reports’). Where a desktop application writes logs depends on the developer, and if the app allows for custom log configuration.
Files are stored in plain-text and can be found in the /var/log directory and subdirectory. There are Linux logs for everything: system, kernel, package managers, boot processes, Xorg, Apache, MySQL. In this article, the topic will focus specifically on Linux system logs.
You can change to this directory using the cd command. You’ll need to be the root user to view or access log files on Linux or Unix-like operating systems.
How to View Linux Logs
Linux logs can be viewed with the command cd/var/log, then by typing the command ls to see the logs stored under this directory. One of the most important logs to view is the syslog, which logs everything but auth-related messages.
Issue the command var/log/syslog to view everything under the syslog, but zooming in on a specific issue will take a while, since this file tends to be long. You can use Shift+G to get to the end of the file, denoted by “END.”
You can also view logs via dmesg, which prints the kernel ring buffer. It prints everything and sends you to the end of the file. From there, you can use the command dmesg | less to scroll through the output. If you want to view log entries for the user facility, you need to issue the command dmesg –facility=user.
Lastly, you can use the tail command to view log files. It is one of the handiest tools you can use, since it only shows the last part of the logs, where the problem usually lies. For this, use the command tail /var/log/syslog or tail -f /var/log/syslog. tail will continue watching the log file, and print out the next line written to the file, allowing you to follow what is written to syslog as it happens. Check out 20 ways to tail a log file post.
For a specific number of lines (example, the last 5 lines) key in tail -f -n 5 /var/log/syslog, which prints the most recent 5 lines. Once a new line comes, the old one gets removed. To escape the tail command, press Ctrl+X.
Most Important Linux Logs
Most directories can be grouped into one of four categories:
- Application Logs
- Event Logs
- Service Logs
- System Logs
Monitoring every log is a monumental task, making tools like Retrace, which combines APM with centralized log management – enabling you to collect all of your log data in one place – essential for developers. The logs that you monitor may depend on your goals or other variables, but there is some consensus about some of the most critical, must-monitor logs, such as:
- /var/log/syslog or /var/log/messages: general messages, as well as system-related information. Essentially, this log stores all activity data across the global system. Note that activity for Redhat-based systems, such as CentOS or Rhel, are stored in messages, while Ubuntu and other Debian-based systems are stored in Syslog.
- /var/log/auth.log or /var/log/secure: store authentication logs, including both successful and failed logins and authentication methods. Again, the system type dictates where authentication logs are stored; Debian/Ubuntu information is stored in /var/log/auth.log, while Redhat/CentrOS is stored in /var/log/secure.
- /var/log/boot.log: a repository of all information related to booting and any messages logged during startup.
- /var/log/maillog or var/log/mail.log: stores all logs related to mail servers, useful when you need information about postfix, smtpd, or any email-related services running on your server.
- /var/log/kern: stores Kernel logs and warning data. This log is valuable for troubleshooting custom kernels as well.
- /var/log/dmesg: messages relating to device drivers. The command dmesg can be used to view messages in this file.
- /var/log/faillog: contains information all failed login attempts, which is useful for gaining insights on attempted security breaches, such as those attempting to hack login credentials as well as brute-force attacks.
- /var/log/cron: stores all Crond-related messages (cron jobs), such as when the cron daemon initiated a job, related failure messages, etc.
- /var/log/yum.log: if you install packages using the yum command, this log stores all related information, which can be useful in determining whether a package and all components were correctly installed.
- /var/log/httpd/: a directory containing error_log and access_log files of the Apache httpd daemon. The error_log contains all errors encountered by httpd. These errors include memory issues and other system-related errors. access_log contains a record of all requests received over HTTP.
- /var/log/mysqld.log or /var/log/mysql.log : MySQL log file that logs all debug, failure and success messages. Contains information about the starting, stopping and restarting of MySQL daemon mysqld. This is another instance where the system dictates the directory; RedHat, CentOS, Fedora, and other RedHat-based systems use /var/log/mysqld.log, while Debian/Ubuntu use the /var/log/mysql.log directory.
What does the output look like? Here’s an example of a Crontab edited by root log:
And here’s a case of Syslogd on Ubuntu (exiting and restarting):
And system shutdown from the Linux kernel:
A few other directories and their uses include:
- /var/log/daemon.log: tracks services running in the background that perform important tasks, but has no graphical output.
- /var/log/btmp: recordings of failed login attempts
- /var/log/utmp: current login state, by user
- /var/log/wtmp: login/logout history
- /var/log/lastlog: information about the last logins for all users. This binary file can be read by command lastlog.
- /var/log/pureftp.log: runs the pureftp process that listens for FTP connections. All connections, FTP logins, and authentication failures get logged here.
- /var/log/spooler: rarely used and often empty. When used, it contains messages from USENET.
- /var/log/xferlog: contains all FTP file transfer sessions, including information about the file name and user initiating FTP transfers.
Understanding the usefulness and limitations of Linux logging is important for any professional working with them. What Linux logs do you consider most important to monitor? Leave your thoughts in the comments below.
Источник