- Topics
- List of Facility independent topics
- Topics used by various RouterOS facilities
- Passthrough
- Настраиваем удаленный сервер rsyslog
- Examples
- Webproxy logging
- Rsyslog
- System/Log
- Profile
- Sniffer
- Log messages
- Mikrotik логирование на удаленный сервер rsyslog
- Summary
- Централизованное логирование Graylog
- Ping
- Connections
- Summary
- Logging to file
- System/Log
- Summary
- Настраиваем пересылку логов в Mikrotik
- Помогла статья? Подписывайся на telegram канал автора
- System/Log
- Actions
- Log messages
- Централизованное логирование Rsyslog
- Logging to file
- Topics
- Log messages
- Examples
- Webproxy logging
- Rsyslog
- Bandwidth Test
- Topics
- ARP
- Summary
- Topics
- IP Scan
- Logging configuration
- Actions
- Как увеличить лог MikroTik
- Traceroute
- Examples
- Webproxy logging
- Rsyslog
- Log messages
- Cable Test
- Очистить лог в MikroTik
- 89 вопросов по настройке MikroTik
- Как сохранить лог MikroTik в файл
- Logging to file
- Log
Topics
Each log entry have topic which describes the origin of log message. There can be more than one topic assigned to log message. For example, OSPF debug logs have four different topics: route, ospf, debug and raw.
List of Facility independent topics
Topics used by various RouterOS facilities
Passthrough
Очень полезная функция, которая ничего не делает.
Допустим, вы хотите заблокировать определённый порт на входящем или проходящем трафике, но переживаете что-то поломать.
Открываем IP – Firewall и создаём правило:


Теперь данное правило ставим выше, предполагаемого блокируемого.
Отправляю эхо-запрос и вижу, что счётчик Bytes и Packets – тикнули. Улавливаете?

Т.е. если есть пакет, подходящий под это правило, мы ничего не делаем, ну кроме тика счётчика. Данная штука так же работает и для маркировки (Mangle). Главное двигайте его правильно.
Настраиваем удаленный сервер rsyslog
У меня в хозяйстве имелся сервер Debian. Решил хранить логи с микротиков именно на нем. В составе Debian уже имеется сервис сбора логов с удаленных источников rsyslog. Необходимо только включить в нем необходимый функционал. Правим файл /etc/rsyslog.conf:
чтобы получать логи по UDP, либо
чтобы получать логи по TCP
И в секцию RULES добавим несколько строк для удобного хранения файлов логов от разных удаленных источников:
Перезапускаем rsyslog для применения настроек:
Теперь наш сервер готов принимать логи с удаленных источников. Хранить он их будет в папке /var/log/!remote Для каждого источника будет создана папка с именем IP адреса этого источника.
Examples
Webproxy logging
These two screenshots will show you how to configure the RouterOS logging facility to send Webrpoxy logs to a remote syslog server, in this example, located at 192.168.100.12. The syslog server can be any software that supports receiving syslogs, for example Kiwi syslog.
Add a new logging action, with «remote» and the IP of the remote server. Call it whatever you like
Then add a new logging rule with the topic «webproxy» and then newly created action. Note that you must have webproxy running on this router already, for this to work. To test, you can temporary change the action to «memory» and see the «log» window if the webproxy visited websites are logged. If it works, change it back to your new remote action
Note: it’s a good idea to add another topic in the same rule: !debug. This would be to ensure you don’t get any debug stuff, only the visited sites.
Rsyslog
It is possible to send all logs to a remote syslog server, one example of a syslog server is Rsyslog. Below you can find configuration example that is relevant to RouterOS:
With this configuration all logs will be present on the device and on the remote syslog server. Below you can find configuration lines that are relevant to a Rsyslog server (only lines that should be changed from the default values):
For security reasons you should only allow Rsyslog to listen to a certain address, this limits the instance to a single interface. You should also specify only certain IP addresses that are allowed to send their logs to the particular syslog server.
Note: Never rely on a single security measure, you should also implement proper Firewall on the machine running Rsyslog, to limit access to the server.
System/Log

Applies to RouterOS: v3, v4 +
Profile
Просмотреть нагрузку на само устройство можно через Profile. У ребят, которые не закрывают DNS снаружи, колонка Usage будет в 100%. Есть возможность фильтрации по ядрам.

Sniffer
Ещё одна полезная фикция в микротик находится Tools – Packet Sniffer позволяет захватывать и анализировать трафик. Доступны разные фильтры.

Сохранять дамп на диск указав максимальный его размер в File Limit. Memory Limit указывает на объем занимаемый в ОЗУ самого снифера.

Так же увидеть направление пакетов, протокол, размер в Packets. И дополнительную информацию в Connections, Hosts, Protocols.

Есть возможность передачи прослушанного трафика на удалённый сервер. Для этих целей подойдёт Wireshark на вашем ПК или ноутбуке.

Доступен так же в CLI. Можно просмотреть входящий/исходящий трафик по определённым портам, очень удобно при диагностировании блокировки L2TP/IPSEC со стороны провайдера, указав их через запятую. Стрелочки, отображают направление.

Log messages
Sub-menu level: /log
All messages stored in routers local memory can be printed from /log menu. Each entry contains time and date when event occurred, topics that this message belongs to and message itself.
If logs are printed at the same date when log entry was added, then only time will be shown. In example above you can see that second message was added on sep/15 current year (year is not added) and the last message was added today so only the time is displayed.
Mikrotik логирование на удаленный сервер rsyslog
Возникло желание собирать логи с роутера Mikrotik. Была нужна информация о подключенных по pptp абонентах и логи firewall для настройки. По-умолчанию, Mikrotik пишет все логи в лог журнал, который можно просмотреть через winbox. Стандартно, там хранятся последние 100 строк лога.
Данная статья является частью единого цикла статьей про Mikrotik.

Summary
RouterOS is capable of logging various system events and status information. Logs can be saved in routers memory (RAM), disk, file, sent by email or even sent to remote syslog server (RFC 3164).
Централизованное логирование Graylog
В идеале, конечно, архитектура должна быть похожа на рисунок ниже, но мы будем придерживаться нашей схемы.
Самым простым сервером здесь не обойдёшься, рекомендуемый минимум выйдет 1828 рублей в месяц. Важно отметить, что для развёртывания необходимо использовать архитектуру процессора AMD64:

Приступим к установке и настройке. База данных:
apt install apt-transport-https openjdk-11-jre-headless uuid-runtime pwgen dirmngr gnupg wget
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | apt-key add -
echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.2 main" | tee /etc/apt/sources.list.d/mongodb-org-4.2.list
apt update
apt install -y mongodb-org
systemctl restart mongodwget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | apt-key add -
echo "deb https://artifacts.elastic.co/packages/oss-7.x/apt stable main" | tee -a /etc/apt/sources.list.d/elastic-7.x.list
apt update && apt install elasticsearch-oss
tee -a /etc/elasticsearch/elasticsearch.yml > /dev/null <<EOT
cluster.name: graylog
action.auto_create_index: false
EOT
systemctl restart elasticsearchwget https://packages.graylog2.org/repo/packages/graylog-4.0-repository_latest.deb
dpkg -i graylog-4.0-repository_latest.deb
apt update
apt install graylog-server graylog-enterprise-plugins graylog-integrations-plugins graylog-enterprise-integrations-plugins
vi /etc/graylog/server/server.conf
password_secret = verySTRONGsecret!! #pwgen -N 1 -s 96
root_username = RUVDS
root_password_sha2 = 2ce2e630e2…..a81521d0f77efa3fe9bc017
#echo -n verySTRONGpassword!! | shasum -a 256
http_bind_address = our_IP_address:9000
http_publish_uri = https://graylog.your_dns_name.ru:9000/
root_timezone = Europe/Moscow
http_enable_tls = true
http_tls_cert_file = /var/keys/graylog_cert.pem
http_tls_key_file = /var/keys/graylog_pkcs8.pemГенерируем ключи для доступа к web интерфейсу по TLS:
vi openssl-graylog.cnf
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = Some-State
L = Some-City
O = My Company
OU = My Division
CN = graylog. your_dns_name.ru
[v3_req]
extendedKeyUsage = serverAuth
subjectAltName = @alt_names [alt_names]
IP.1 = our_IP_address
DNS.1 = graylog. your_dns_name.ru
openssl req -x509 -days 365 -nodes -newkey rsa:2048 -config /root/openssl-graylog.cnf -keyout /var/keys/graylog_pkcs5.pem -out /var/keys/graylog_cert.pem
openssl pkcs8 -in /var/keys/graylog_pkcs5.pem -topk8 -nocrypt -out /var/keys/graylog_pkcs8.pem
chmod 644 /var/keys/graylog_pkcs8.pem
cp -a "${JAVA_HOME}/jre/lib/security/cacerts" /vat/keys/cacerts.jks
cp -a /usr/share/elasticsearch/jdk/lib/security/cacerts /var/keys/cacerts.jks
keytool -importcert -keystore /var/keys/cacerts.jks -storepass changeit -alias graylog-self-signed -file /var/keys/graylog_cert.pem
keytool -keystore /var/keys/cacerts.jks -storepass changeit -list | grep graylog-self-signed -A1
vi /etc/default/graylog-server
GRAYLOG_SERVER_JAVA_OPTS="... -Djavax.net.ssl.trustStore=/var/keys/cacerts.jks"
systemctl restart graylog-serverЕсли всё прошло корректно, то можно будет увидеть такой вот web интерфейс, протокол HTTPS (graylog.your_dns_name.ru:9000):


Чтобы получать сообщения от первичного коллектора по UDP, необходимо настроить вводы нашего Graylog, примерно так:

У нас уже всё готово для общения по TLS, поэтому просто выбираем соответствующий режим и заполняем необходимые поля. Как совет, не пытайтесь перенести веб-морду на 443 порт (ни NAT-ом, ни с помощью прокси), столкнётесь с проблемами на уровне API. В результате просматривать логи стало гораздо приятнее:


В конечном итоге мы рекомендуем вкладывать получение сообщений от первичного коллектора по TLS в VPN канал, тогда открытый TCP порт не будет светиться в интернет, и не будет сохраняться флуд, вроде такого:

Здесь нужно дополнительно рассказать не только о важности и способе, хранении и анализе логов, но так же и о такой вещи, как развёртывание «черного ящика», который будет собирать информацию обо всех сетевых соединениях. Это поможет восстановить полную хронологию событий, в случае компрометации системы. Мы рекомендуем использовать для этого протокол .
Активируем его в RouterOS и указываем IP адрес коллектора:
/ip traffic-flow set enabled=yes interfaces=bridge
/ip traffic-flow target add dst-address=192.168.15.1 port=1234 version=5Настраиваем принимающую сторону – netflow коллектор:
mkdir /var/log/flow
vi /etc/flow-tools/flow-capture.conf
-w /var/log/flow -n 275 -N 3 192.168.15.1/0/1234
systemctl restart flow-captureПросмотрим получаемую статистику:
flow-cat /var/log/flow/2020/2020-10/*/ft-* | flow-stat
Total Flows : 324
Total Octets : 59866191
Total Packets : 42896
Total Time (1/1000 secs) (flows): 3029440
Duration of data (realtime) : 290
Duration of data (1/1000 secs) : 340200
Average flow time (1/1000 secs) : 9350.1230
Average packet size (octets) : 1395.6124
Average flow size (octets) : 184772.2031
Average packets per flow : 132.3951
Average flows / second (flow) : 0.9529
Average flows / second (real) : 1.1172
Average Kbits / second (flow) : 1408.6162
Average Kbits / second (real) : 1651.4812Непосредственно результаты накопления можно увидеть таким образом:
flow-cat /var/log/flow/2020/2020-10/2020-10-31/ft-v05.2020-10-31.122757+0300 | flow-export -f 2
1604136477,821825000,103238050,192.168.15.5,1,60,103221520,103221520,0,0,17.248.150.106,192.168.2.254,192.168.2.254,11,10,443,65448,6,104,18,0,0,0,0
1604136477,821825000,103238050,192.168.15.5,17,9395,103219730,103222300,0,0,17.248.150.51,192.168.2.254,192.168.2.254,11,10,443,65446,6,104,18,0,0,0,0
1604136480,821818000,103241050,192.168.15.5,20,8786,103221270,103224760,0,0,17.248.15Сохраняемые объёмы выходят небольшими. Своего рода биллинг сетевых соединений, проходящих через маршрутизатор.
Ping
Tools — Ping
Простенькая тулза, с дополнительными фишками по аналогии с Traceroute. Позволяет сделать пинг на L2 – ARP-Ping. Для этого нужно выбрать интерфейс. На скриншоте видно стабильное время отклика до моего ноутбука, подключённого через WiFi.

Connections
Если ваш роутер, настроен на преобразование адресов, или по-русски, есть хотя бы одно правило NAT, то включается тот самый Connection Tracker. С помощью его фильтров, можно просматривать состояние соединений.
Открываем IP – Firewall – Connections, нажимаем на фильтр:
Я хочу просмотреть все соединения с 192.168.10.51
![]()
Тут можно увидеть новые, устоявшиеся и любые другие соединения. В колонке Connection Mark отображается метки пакетов – удобно диагностировать при Dual WAN.
Summary
RouterOS is capable of logging various system events and status information. Logs can be saved in routers memory (RAM), disk, file, sent by email or even sent to remote syslog server (RFC 3164).
Logging to file
To log everything to file, add new log action:
and then make everything log using this new action:
You can log only errors there by issuing command:
This will log into files log.0.txt and log.1.txt.
You can specify maximum size of file in lines by specifying disk-lines-per-file. .0.txt is active file were new logs are going to be appended and once it size will reach maximum it will become .1.txt, and new empty .0.txt will be created.
Note: Logging entries from files will be stored back in the memory after reboot.
System/Log

Applies to RouterOS: v3, v4 +
Summary
RouterOS is capable of logging various system events and status information. Logs can be saved in routers memory (RAM), disk, file, sent by email or even sent to remote syslog server (RFC 3164).
Настраиваем пересылку логов в Mikrotik
Теперь настраиваем в роутере хранение логов на удаленном сервере. Для этого заходим в раздел System -> Logging, выбираем закладку Actions, два раза щелкаем по строчке remote. Открывается окно настроек. В нем вводим адрес удаленного сервера сбора логов. Порт на свое усмотрение либо оставляем по-умолчанию, либо меняем на свой. Больше ничего добавлять не надо.

Дальше в разделе Rules создаем необходимое правило хранения:

Все готово. Теперь все наши логи будут храниться на удаленном сервере. Необходимо не забыть настроить ротацию логов, дабы в один прекрасный день они не заняли все свободное место.

Если вы используете ELK Stack для централизованного сбора логов, то у меня есть статья по отправке логов mikrotik в elk stack.
Напоминаю, что данная статья является частью единого цикла статьей про Mikrotik.
Помогла статья? Подписывайся на telegram канал автора
Рекомендую полезные материалы по схожей тематике:
System/Log

Applies to RouterOS: v3, v4 +
Actions
Sub-menu level: /system logging action
Log messages
Sub-menu level: /log
All messages stored in routers local memory can be printed from /log menu. Each entry contains time and date when event occurred, topics that this message belongs to and message itself.
If logs are printed at the same date when log entry was added, then only time will be shown. In example above you can see that second message was added on sep/15 current year (year is not added) and the last message was added today so only the time is displayed.
Print command accepts several parameters that allows to detect new log entries, print only necessary messages and so on.
Централизованное логирование Rsyslog
Регулярный анализ логов – важная задача в поддержании должного уровня информационной безопасности. Каждый раз заходить на MikroTik-и и просматривать, что же там новенького, с учётом удаления старых записей, совсем неинтересно, поэтому важно собирать всё в едином месте. Со стороны RouterOS это делается просто:
/system logging
add action=remote topics=critical
add action=remote topics=error
add action=remote topics=info
add action=remote topics=warning
/system logging action set 3 remote=10.0.0.10apt install rsyslog
vi /etc/rsyslog.conf
#provides UDP syslog reception
module(load="imudp")
input(type="imudp" port="514")
if $fromhost-ip == '192.168.1.1' then { /var/log/mikrotik.log *.* @192.168.15.29:2000
}
if $fromhost-ip == '192.168.1.14' then { /var/log/cisco.log *.* @192.168.15.29:2001
}В качестве транспортного протокола выбран не шифрованный UDP, порт 514. Сообщения от роутера MikroTik (IP адрес 192.168.1.1) будут сохраняться на коллекторе в файле /var/log/mikrotik.log, а также ретранслироваться по UDP на коллектор второго уровня на порт 2000. Сообщения от роутера, например, Cisco (IP адрес 192.168.1.14) будут сохраняться на коллекторе в файле /var/log/cisco.log, а также ретранслироваться по UDP на коллектор второго уровня на порт 2001. Гонять логи по открытому каналу – плохая идея, ведь по ним можно установить полную карту вашей сети, найти в ней слабые места или даже изъяны в информационной безопасности. Поэтому передачу вложим в закрытый VPN туннель. Особых требований к ресурсам сервера не предъявляются, поэтому для тестов можно использовать самый простой VPS:

Коллектор второго уровня будет собирать логи со всей администрируемой сети и ориентироваться по доменному имени устройства, сохранённого коллектором первого уровня:
vi /etc/rsyslog.conf
module(load="imudp")
input(type="imudp" port="514")
$UDPServerAddress 192.168.15.41
if $source == 'cisco.lan' then { /var/log/cisco.log
}
if $source == 'router.lan' then { /var/log/mikrotik.log
}
systemctl restart rsyslogВ качестве переменных можно использовать:
- msg – тело сообщения;
- hostname – имя хоста, отправившего сообщение;
- source – алиас hostname (как показано в примере);
- fromhost – имя хоста, от которого было получено сообщение;
- fromhost-ip – то же самое, что и fromhost, только всегда ip-адрес;
- programname – имя программы;
- syslogfacility – источник лог сообщения в форме цифры;
- syslogfacility-text – источник лог сообщения в текстовой форме;
- syslogseverity – уровень важности в цифровом виде;
- syslogseverity-text – уровень важности в текстовом виде;
- pri – источник и приоритет в виде числа;
- pri-text – источник и приоритет в текстовом формате;
- timegenerated – время, когда сообщение было получено.
Это скелет нашей модели, настало время нарастить его мышцами. Гонять открытые логи даже по шифрованному VPN туннелю тоже не стоит, ведь и его кто-то где-то может прослушивать. Поэтому организуем передачу по TLS протоколу, вместо применяемого ранее UDP. Первым делом подготовим ключи и сертификаты:
apt install gnutls-bin rsyslog-gnutlscerttool --generate-privkey --outfile /var/keys/ca-key.pem
certtool --generate-self-signed --load-privkey /var/keys/ca-key.pem --outfile /var/keys/ca.pem
Common name: ca
The certificate will expire in (days): 3650
Does the certificate belong to an authority? (y/N): y
Will the certificate be used to sign other certificates? (y/N): y
Is the above information ok? (Y/N): ycerttool --generate-privkey --outfile /var/keys/rslclient-key.pem --bits 2048
We will generate now the certification request ---> TLS CLIENT
Common name: client.log.your_dns_name.ru
Will the certificate be used for signing (DHE and RSA-EXPORT ciphersuites)? (Y/n): N
Is this a TLS web client certificate? (y/N): y
Is this also a TLS web server certificate? (y/N): ycerttool --generate-request --load-privkey /var/keys/rslclient-key.pem --outfile /var/keys/request.pem
Common name: client.log.your_dns_name.ru
Does the certificate belong to an authority? (y/N): n
Will the certificate be used for signing (DHE and RSA-EXPORT ciphersuites)? (Y/n): N
Is this a TLS web client certificate? (y/N): y
Is this also a TLS web server certificate? (y/N): yПодпись клиентского сертификата:
certtool --generate-certificate --load-request /var/keys/request.pem --outfile /var/keys/rslclient-cert.pem --load-ca-certificate /var/keys/ca.pem --load-ca-privkey /var/keys/ca-key.pem
The certificate will expire in (days): 365
Will the certificate be used for signing (DHE and RSA-EXPORT ciphersuites)? (Y/n): N
Is this a TLS web client certificate? (y/N): y
Is this also a TLS web server certificate? (y/N): y
rm /var/keys/request.pemСерверный ключ (2048 бит нам вполне хватит):
certtool --generate-privkey --outfile /var/keys/rslserver-key.pem --bits 2048certtool --generate-request --load-privkey /var/keys/rslserver-key.pem --outfile /var/keys/request.pem
Common name: log.your_dns_name.ru
Enter a dnsName of the subject of the certificate: log.your_dns_name.ru
Will the certificate be used for signing (DHE and RSA-EXPORT ciphersuites)? (Y/n): N
Is this a TLS web client certificate? (y/N): y
Is this also a TLS web server certificate? (y/N): yПодпись серверного сертификата:
certtool --generate-certificate --load-request /var/keys/request.pem --outfile /var/keys/rslserver-cert.pem --load-ca-certificate /var/keys/ca.pem --load-ca-privkey /var/keys/ca-key.pem
The certificate will expire in (days): 365
Enter a dnsName of the subject of the certificate: log.your_dns_name.ru
Will the certificate be used for signing (DHE and RSA-EXPORT ciphersuites)? (Y/n): N
Is this a TLS web client certificate? (y/N): y
Is this also a TLS web server certificate? (y/N): y
rm /var/keys/request.pem
chmod 644 /var/keys/*
chmod 400 /var/keys/ca-key.pemПравим конфиг для первичного коллектора. Принимает сообщения от роутеров так же по UDP (может оказаться единственным универсальным решением для всего зоопарка), сохраняем в локальные файлы mikrotik.log и cisco.log и ретранслируем уже по TLS за пределы охраняемого нами периметра на сервер log.your_dns_name.ru:
vi /etc/rsyslog.conf
module(load="imudp")
input(type="imudp" port="514")
$DefaultNetstreamDriver gtls
$DefaultNetstreamDriverCAFile /var/keys/ca.pem
$DefaultNetstreamDriverCertFile /var/keys/rslclient-cert.pem
$DefaultNetstreamDriverKeyFile /var/keys/rslclient-key.pem
$ActionSendStreamDriverPermittedPeer log. your_dns_name.ru
$ActionSendStreamDriverMode 1
$ActionSendStreamDriverAuthMode x509/name
if $fromhost-ip == '192.168.1.1' then { /var/log/mikrotik.log
*.* @@log.your_dns_name.ru:514
}
if $fromhost-ip == '192.168.1.14' then {
/var/log/cisco.log
*.* @@log.your_dns_name.ru:514
}Вносим изменения на вторичном сервере логирования log.your_dns_name.ru:
vi /etc/rsyslog.conf
$ModLoad imtcp
$DefaultNetstreamDriver gtls
$DefaultNetstreamDriverCAFile /var/keys/ca.pem
$DefaultNetstreamDriverCertFile /var/keys/rslserver-cert.pem
$DefaultNetstreamDriverKeyFile /var/keys/rslserver-key.pem
$InputTCPServerStreamDriverAuthMode anon
$InputTCPServerStreamDriverMode 1
$ActionSendStreamDriverAuthMode x509/name
$ActionSendStreamDriverPermittedPeer *
$ActionSendStreamDriverMode 1
$InputTCPServerRun 514
$MaxOpenFiles 2048
if $source == 'cisco.lan' then { /var/log/cisco.log
}
if $source == 'router.lan' then { /var/log/mikrotik.log
}
systemctl restart rsyslogЗдесь уже, возможно, понадобится траблшутинг для обоих коллекторов. Для этого можно воспользоваться анализатором сетевых пакетов tcpdump, попробовать подключиться в нашему серверу извне по TLS, а также просмотреть запущенные демоны и прослушиваемые ими сетевые интерфейсы и порты:
tcpdump -i eth0 -n "dst port 514"
openssl s_client -connect graylog.your_dns_name.ru:514
netstat –tlnpПодведём промежуточный итог. Программное обеспечение настроили. Логи собираем в два этапа. Коллектор первого уровня работает внутри защищаемого периметра, коллектор второго уровня отвечает за всю сеть в целом. Логи просматриваем примерно так:
cat /var/log/mikrotik.log | grep "login failure"
Apr 20 18:21:18 192.168.15.13 system,error,critical login failure for user admin from 192.168.15.5 via winboxРезультат есть, но админу работать так не хочется, поэтому пойдём ещё дальше и прикрутим в нашу историю красивый, удобный и функциональный интерфейс, а именно развернём решение на базе .
Logging to file
To log everything to file, add new log action:
and then make everything log using this new action:
Topics
Each log entry have topic which describes the origin of log message. There can be more than one topic assigned to log message. For example, OSPF debug logs have four different topics: route, ospf, debug and raw.
List of Facility independent topics
Topics used by various RouterOS facilities
Log messages
Sub-menu level: /log
All messages stored in routers local memory can be printed from /log menu. Each entry contains time and date when event occurred, topics that this message belongs to and message itself.
If logs are printed at the same date when log entry was added, then only time will be shown. In example above you can see that second message was added on sep/15 current year (year is not added) and the last message was added today so only the time is displayed.
Examples
Webproxy logging
These two screenshots will show you how to configure the RouterOS logging facility to send Webrpoxy logs to a remote syslog server, in this example, located at 192.168.100.12. The syslog server can be any software that supports receiving syslogs, for example Kiwi syslog.
Add a new logging action, with «remote» and the IP of the remote server. Call it whatever you like
Then add a new logging rule with the topic «webproxy» and then newly created action. Note that you must have webproxy running on this router already, for this to work. To test, you can temporary change the action to «memory» and see the «log» window if the webproxy visited websites are logged. If it works, change it back to your new remote action
Note: it’s a good idea to add another topic in the same rule: !debug. This would be to ensure you don’t get any debug stuff, only the visited sites.
Rsyslog
It is possible to send all logs to a remote syslog server, one example of a syslog server is Rsyslog. Below you can find configuration example that is relevant to RouterOS:
With this configuration all logs will be present on the device and on the remote syslog server. Below you can find configuration lines that are relevant to a Rsyslog server (only lines that should be changed from the default values):
For security reasons you should only allow Rsyslog to listen to a certain address, this limits the instance to a single interface. You should also specify only certain IP addresses that are allowed to send their logs to the particular syslog server.
Note: Never rely on a single security measure, you should also implement proper Firewall on the machine running Rsyslog, to limit access to the server.
Bandwidth Test
Bandwidth Test Клиент-серверная утилита созданная компанией mikrotik, позволяет проверить скорость соединения между устройствами по протоколу UDP (порт 2000). Достаточно сильно нагружает процессор на больших скоростях иди маленьких ЦП. Есть инструмент для скачивания на Windows, а также общедоступные сервера в интернете. Доступен в меню Tools.


В самом низу представлен удобный график. Можете мерить скорости внутри VPN или LAN, между мостами и офисами или промежуточных узлов.
Topics
Each log entry have topic which describes the origin of log message. There can be more than one topic assigned to log message. For example, OSPF debug logs have four different topics: route, ospf, debug and raw.
List of Facility independent topics
Topics used by various RouterOS facilities
ARP
IP – ARP-List
Таблица ARP адресов доступна на просмотр соответствий. Можно создать постоянную запись соответствия IP к MAC.

Summary
RouterOS is capable of logging various system events and status information. Logs can be saved in routers memory (RAM), disk, file, sent by email or even sent to remote syslog server (RFC 3164).
Topics
Each log entry have topic which describes the origin of log message. There can be more than one topic assigned to log message. For example, OSPF debug logs have four different topics: route, ospf, debug and raw.
List of Facility independent topics
Topics used by various RouterOS facilities
IP Scan
Маленькая утилита, позволит узнать, какая подсеть/подсети или адреса видны на определённых интерфейсах.
Попробуем выяснить, что живёт на провайдером интерфейсе самого крупного оператора нашей страны.
Если вы хотите просканировать определённую подсеть, то можете ее указать в Address Range.

Как только я получил данный адрес, мой порт тут отключился. Позвонив в ТП, меня уверяли, что никаких блокировок на порту нет и т.д. и т.п. Оператор утверждала, что проблема в обрыве кабеля. Давайте проверим кабель.
Logging configuration
Sub-menu level: /system logging
Actions
Sub-menu level: /system logging action
Note: default actions can not be deleted or renamed.
Как увеличить лог MikroTik
Текущий лог устройства MikroTik выводится в виде списка, состоящий из событий, определенных в настройках System->Logging. Как правило количество строк по умолчанию 100 и этого бывает недостаточно, чтобы провести зафиксировать интересующие событие. Для изменения нужно поменять значение Lines.
Настройка находится в System->Logging

Traceroute
Tools — Traceroute
Графическая утилита, для определения количества хопов по пути. Фишка ее в том, что она постоянно будет рисовать потери, историю и время до хопа.

Вы можете указать максимальное количество прыжков, исходящий адрес, таблицу маршрутизации, интерфейс и размер пакета.
Examples
Webproxy logging
These two screenshots will show you how to configure the RouterOS logging facility to send Webrpoxy logs to a remote syslog server, in this example, located at 192.168.100.12. The syslog server can be any software that supports receiving syslogs, for example Kiwi syslog.
Add a new logging action, with «remote» and the IP of the remote server. Call it whatever you like
Then add a new logging rule with the topic «webproxy» and then newly created action. Note that you must have webproxy running on this router already, for this to work. To test, you can temporary change the action to «memory» and see the «log» window if the webproxy visited websites are logged. If it works, change it back to your new remote action
Note: it’s a good idea to add another topic in the same rule: !debug. This would be to ensure you don’t get any debug stuff, only the visited sites.
Rsyslog
It is possible to send all logs to a remote syslog server, one example of a syslog server is Rsyslog. Below you can find configuration example that is relevant to RouterOS:
With this configuration all logs will be present on the device and on the remote syslog server. Below you can find configuration lines that are relevant to a Rsyslog server (only lines that should be changed from the default values):
For security reasons you should only allow Rsyslog to listen to a certain address, this limits the instance to a single interface. You should also specify only certain IP addresses that are allowed to send their logs to the particular syslog server.
Note: Never rely on a single security measure, you should also implement proper Firewall on the machine running Rsyslog, to limit access to the server.
Log messages
Sub-menu level: /log
All messages stored in routers local memory can be printed from /log menu. Each entry contains time and date when event occurred, topics that this message belongs to and message itself.
If logs are printed at the same date when log entry was added, then only time will be shown. In example above you can see that second message was added on sep/15 current year (year is not added) and the last message was added today so only the time is displayed.
Cable Test
Да, Mikrotik умеет диагностировать разрыв физической линии с помощью утилиты Cable Test, причём довольно точно. После разговора с оператором, я запустил данную утилиту. Картина интересна, по трём парам 94 метра, а по одной 98, и все они разорваны на одинаковом расстоянии от меня.

Полагаю, что оператор был не прав (оно и очевидно), т.к. мой линк снова загорелся, спустя 5 минут.
Будьте осторожны, подобные ситуации, могут быть и у вас.
Очистить лог в MikroTik
Для удалениея лога на роутере MikroTik необходимо последовательно выполнить две команды:
- первая сократит количество строк до 1шт;
- вторая – увеличит до 1000шт.
/system logging action set memory memory-lines=1; /system logging action set memory memory-lines=1000;
Весь лог, который окажется до выполнения 1-ой команды будет сокращен(удалён) до одной строки, а вторая команда восстановить нормальный размер лога.
89 вопросов по настройке MikroTik
Вы хорошо разбираетесь в Микротиках? Или впервые недавно столкнулись с этим оборудованием и не знаете, с какой стороны к нему подступиться? В обоих случаях вы найдёте для себя полезную информацию в курсе «Настройка оборудования MikroTik». 162 видеоурока, большая лабораторная работа и 89 вопросов, на каждый из которых вы будете знать ответ. Подробности и доступ к началу курса бесплатно тут.
Как сохранить лог MikroTik в файл
Консоль System->Logging не имеет функционала поиска или фильтрации по событиям, что доставляет ряд неудобств при диагностике. Решить эту проблему можно с помощью команд:
для вывода текущего лога в терминал(доступ буфер обмена)
/log print
или в файл флеш памяти
/log print file=log
Logging to file
To log everything to file, add new log action:
and then make everything log using this new action:
You can log only errors there by issuing command:
This will log into files log.0.txt and log.1.txt.
You can specify maximum size of file in lines by specifying disk-lines-per-file. .0.txt is active file were new logs are going to be appended and once it size will reach maximum it will become .1.txt, and new empty .0.txt will be created.
Note: Logging entries from files will be stored back in the memory after reboot.
Log
Логирование основных действий пишется в ОЗУ и хранится до перезагрузки устройства. Вот тут, помимо засвеченных маков, можно увидеть, что WAN интерфейс поднялся и через 40 секунд отключился основной провайдерский линк.
Вы можете детализировать отображаемую информацию через System – Logging. На примере ниже, я добавил хранение в ОЗУ всех DNS запросов. Лог сразу же стал быстро заполняться и пролистываться.
Для приостановки автопролистывания есть кнопка Freeze, она замораживает автоскролинг.

В Actions, вы можете настроить отправку логов на удалённый Syslog Server, или хранить их локально на диске.
Не сложными манипуляциями возможно сделать debug определённых служб, допустим DHCP.
Берите на вооружение, очень полезная штука.

