Community discussions

MikroTik App
 
User avatar
katem07
just joined
Topic Author
Posts: 17
Joined: Mon Apr 10, 2017 11:35 am
Location: SAR
Contact:

Monitor Mikrotik log by Telegram

Sun Sep 08, 2019 1:42 pm

Hey, If you want to monitor your Mikrotik log's Specific event's like : excessive broadcast,loop,link down,fcs errors,and even failure login attempts to your server

this method is going to help you as it helped me to monitor +40 Mikrotik server under my control for more than one year in a perfect experiment 8)

you can filter your log's parameters and this method will send all event's about it to your telegram group like a notification :o

Now here is a simple Script with an auto scheduler running every one minute (you can edit it as you like)

Here is the steps:
1-add new script with name "LogFilter"
2-Copy and past the code below
3-edit setup section to your own telegram bot and chat id
4-run the script for first time by your self allowing it to run every one minute
# LOG FILTER TO TELEGRAM BY AHMED MOUSELLY
# BEGIN SETUP Edit Here
:local myserver ([/system identity get name])
:local scheduleName "LogFilter"
:local bot "your bot id"
:local ChatID "-your chat id"
:local startBuf [:toarray [/log find message~" failure" || message~"loop" || message~"down" || message~"fcs" || message~"excessive"]]

# END SETUP

# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."

 /system scheduler add name=$scheduleName interval=60s start-date=Jul/05/2019 start-time=startup on-event=LogFilter

  /log warning "[LogFilter] Alert : Schedule created ."
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
 
# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
 
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
    
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." %0A%0A ".$message."\r\n")
   }

    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
  :if ($counter = ([:len $startBuf]-1)) do={
   :if ($keepOutput = false) do={    
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTimer." ".$message."\r\n")
      }
    }
  }
  :set counter ($counter + 1)
}

if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool fetch url="https://api.telegram.org/bot$bot/sendmessage?chat_id=$ChatID&text=$myserver%0A%0A$output" keep-result=no;
}
Note 1: This code will not repeat the same event twice, it takes the last date of the event and saves it and remember to not repeat it again till it appears again in log.


Note 2: Quoted and modified code
Regards.
Knowledge Sharing ... :idea: :wink:
  • Facebook:Fb.com/katem07
  • Ahmed Mosilly
  • Regards.
 
MisterFTTH
just joined
Posts: 4
Joined: Sat Mar 30, 2019 1:18 am

Re: Monitor Mikrotik log by Telegram

Sun Jun 07, 2020 5:46 pm

HI katem07, I used to rely on your great script (vanilla) for almost a year now but yesterday it stopped working all of a sudden without me having changed any settings: script counter is increasing and no error message is being logged but no message is being delivered, I tried reboot/upgrade with no luck, sadly...BTW I get no problem in sending a message manually via browser URL or ROS console...any hint?

Thanks in advance!
 
User avatar
BergDev
just joined
Posts: 14
Joined: Thu Mar 05, 2020 4:27 pm
Location: Russia

Re: Monitor Mikrotik log by Telegram

Thu Jul 09, 2020 5:54 pm

I tested the script on my RB750 GR3, the script filters logs perfectly, but I finished it a little with the 6.46 ROS update. Adding an updated version.
# LOG FILTER TO TELEGRAM BY AHMED MOUSELLY//UPD.09.07.2020BergDev
# BEGIN SETUP Edit Here
:local myserver ([/system identity get name])
:local scheduleName "LogFilter"
:local bot "WRITE YOUR BOTID"
:local ChatID "WRITE YOUR CHAT ID"
#Here you can specify which events from the logs you need to send.
:local startBuf [:toarray [/log find message~" failure" || message~"loop"|| message~"sent" || message~"down" || message~"fcs" || message~"excessive"]]

# END SETUP

# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."

 /system scheduler add name=$scheduleName interval=60s start-date=Jul/09/2020 start-time=startup on-event=LogFilter

  /log warning "[LogFilter] Alert : Schedule created ."
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
 
# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
 
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
    
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." %0A%0A ".$message."\r\n")
   }

    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
  :if ($counter = ([:len $startBuf]-1)) do={
   :if ($keepOutput = false) do={    
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTimer." ".$message."\r\n")
      }
    }
  }
  :set counter ($counter + 1)
}

if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool fetch url="https://api.telegram.org/bot$bot/sendMessage\?chat_id=$ChatID&text=$myserver%0A%0A$output" keep-result=no;
}
 
User avatar
BergDev
just joined
Posts: 14
Joined: Thu Mar 05, 2020 4:27 pm
Location: Russia

Re: Monitor Mikrotik log by Telegram

Sat Jul 11, 2020 8:54 pm

I noticed a bug in the script, notifications from the log are not parsed immediately, but with a delay, or they are not parsed at all, I will try to fix it.
 
Lilarcor
Frequent Visitor
Frequent Visitor
Posts: 52
Joined: Sun Oct 08, 2017 3:16 am

Re: Monitor Mikrotik log by Telegram

Tue Jul 28, 2020 4:12 pm

I have other scripts to downloaded txt files and which leaves "downloaded" in log. How can I ignore "downloaded" but keep "down" in the monitor script?
 
MisterFTTH
just joined
Posts: 4
Joined: Sat Mar 30, 2019 1:18 am

Re: Monitor Mikrotik log by Telegram

Fri Aug 07, 2020 12:45 pm

I noticed a bug in the script, notifications from the log are not parsed immediately, but with a delay, or they are not parsed at all, I will try to fix it.
Thanks for your effort!
 
User avatar
neck
just joined
Posts: 3
Joined: Wed Feb 14, 2018 9:43 am
Location: RUS Zhukovsky
Contact:

Re: Monitor Mikrotik log by Telegram

Sat Oct 31, 2020 11:20 am

I tested the script on my RB750 GR3, the script filters logs perfectly, but I finished it a little with the 6.46 ROS update. Adding an updated version.
...
# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."

 /system scheduler add name=$scheduleName interval=60s start-date=Jul/09/2020 start-time=startup on-event=LogFilter

  /log warning "[LogFilter] Alert : Schedule created ."
}
...

Can I let User determine the script execution schedule? =)
And do not create it to run once a minute.
...
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LOGMON] ERROR: Schedule does not exist. Create schedule and edit script to match name: $scheduleName"
}

# delete this /system scheduler add name=$scheduleName interval=60s start-date=Jul/09/2020 start-time=startup on-event=LogFilter
# delete this /log warning "[LogFilter] Alert : Schedule created ."
 

...
 
imad
just joined
Posts: 3
Joined: Mon Aug 25, 2014 8:49 pm

Re: Monitor Mikrotik log by Telegram

Mon Nov 23, 2020 12:38 pm

I tried it on HEX works fine and thank you
But I put the same settings on CCR 1036 It didn't work
is there a solution
 
ksteink
Frequent Visitor
Frequent Visitor
Posts: 74
Joined: Thu Mar 31, 2016 6:54 pm

Re: Monitor Mikrotik log by Telegram

Tue Nov 24, 2020 11:43 pm

Nice script. I am using it in multiple devices and works like a charm


Sent from my iPhone using Tapatalk
 
User avatar
BergDev
just joined
Posts: 14
Joined: Thu Mar 05, 2020 4:27 pm
Location: Russia

Re: Monitor Mikrotik log by Telegram

Wed Nov 25, 2020 7:50 am

I tried it on HEX works fine and thank you
But I put the same settings on CCR 1036 It didn't work
is there a solution
Yes, they wrote me about this bug, I'm currently checking the script on different hardware.
 
User avatar
BergDev
just joined
Posts: 14
Joined: Thu Mar 05, 2020 4:27 pm
Location: Russia

Re: Monitor Mikrotik log by Telegram

Wed Nov 25, 2020 7:52 am

I tested the script on my RB750 GR3, the script filters logs perfectly, but I finished it a little with the 6.46 ROS update. Adding an updated version.
...
# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."

 /system scheduler add name=$scheduleName interval=60s start-date=Jul/09/2020 start-time=startup on-event=LogFilter

  /log warning "[LogFilter] Alert : Schedule created ."
}
...

Can I let User determine the script execution schedule? =)
And do not create it to run once a minute.
...
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LOGMON] ERROR: Schedule does not exist. Create schedule and edit script to match name: $scheduleName"
}

# delete this /system scheduler add name=$scheduleName interval=60s start-date=Jul/09/2020 start-time=startup on-event=LogFilter
# delete this /log warning "[LogFilter] Alert : Schedule created ."
 

...
The script execution schedule directly depends on the time when the log is sent to the telegram chat. you can try changing the script execution time.
 
kivimart
newbie
Posts: 49
Joined: Thu Oct 10, 2013 3:06 pm

Re: Monitor Mikrotik log by Telegram

Fri May 28, 2021 9:22 am

I have other scripts to downloaded txt files and which leaves "downloaded" in log. How can I ignore "downloaded" but keep "down" in the monitor script?
Find any solution to this .?
 
666blade666
just joined
Posts: 10
Joined: Tue Feb 09, 2016 10:51 pm

Re: Monitor Mikrotik log by Telegram

Wed Jun 30, 2021 5:26 pm

Does not work on rb4011
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 7050
Joined: Tue Feb 25, 2014 12:49 pm
Location: Italy, but my Heart is in Україна

Re: Monitor Mikrotik log by Telegram

Wed Jun 30, 2021 5:36 pm

Why make a script that has to create a scheduler to launch the script that then one of the two doesn't work and you waste time figuring out where the problem is ???

The script simply puts itself off the scheduler instead of doing all this ping-pong and checking if the scheduler exists or not.
 
666blade666
just joined
Posts: 10
Joined: Tue Feb 09, 2016 10:51 pm

Re: Monitor Mikrotik log by Telegram

Wed Jun 30, 2021 6:09 pm

You have a script that can send logs to a telegram, similar to this? To select which criteria to send (example: critical, failure, warning)...
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 7050
Joined: Tue Feb 25, 2014 12:49 pm
Location: Italy, but my Heart is in Україна

Re: Monitor Mikrotik log by Telegram

Wed Jun 30, 2021 6:13 pm

I do not make script what I can not test.
I do not have telegram,
but if you SEARCH my previous posts I already helped other authors to fix script for similar manner.
 
666blade666
just joined
Posts: 10
Joined: Tue Feb 09, 2016 10:51 pm

Re: Monitor Mikrotik log by Telegram

Thu Jul 01, 2021 10:08 am

Can you help me with this one? On RB4011 do not work... =((
# LOG FILTER TO TELEGRAM
# BEGIN SETUP Edit Here
:local myserver ([/system identity get name])
:local scheduleName "LogFilter"
:local bot "941325023:AAH-pNTxLr021Av_C7bc9IGVdZDchDlwGb0"
:local ChatID "-262862011"
#Here you can specify which events from the logs you need to send.
:local startBuf [:toarray [/log find message~" failure" || message~"loop" || message~"critical" || message~"error" || message~"fcs" || message~"excessive"]]

# END SETUP

# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
/log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."

/system scheduler add name=$scheduleName interval=300s start-date=Jul/09/2020 start-time=startup on-event=LogFilter

/log warning "[LogFilter] Alert : Schedule created ."
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message

# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
:set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={

# loop through all removeThese array items
:local keepLog true
:foreach j in=$removeThese do={
# if this log entry contains any of them, it will be ignored
:if ([/log get $i message] ~ "$j") do={
:set keepLog false
}
}
:if ($keepLog = true) do={

:set message [/log get $i message]

# LOG DATE
# depending on log date/time, the format may be different. 3 known formats
# format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
:set currentTime [ /log get $i time ]
# format of 00:00:00 which shows up on current day's logs
:if ([:len $currentTime] = 8 ) do={
:set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
} else={
# format of jan/01 00:00:00 which shows up on previous day's logs
:if ([:len $currentTime] = 15 ) do={
:set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
}
}

# if keepOutput is true, add this log entry to output
:if ($keepOutput = true) do={
:set output ($output.$currentTime." %0A%0A ".$message."\r\n")
}

:if ($currentTime = $lastTime) do={
:set keepOutput true
:set output ""
}
}
:if ($counter = ([:len $startBuf]-1)) do={
:if ($keepOutput = false) do={
:if ([:len $message] > 0) do={
:set output ($output.$currentTimer." ".$message."\r\n")
}
}
}
:set counter ($counter + 1)
}

if ([:len $output] > 0) do={
/system scheduler set [find name="$scheduleName"] comment=$currentTime
/tool fetch url="https://api.telegram.org/bot$bot/sendme ... %0A$output" keep-result=no;
}
 
MohamedTaltlo
just joined
Posts: 1
Joined: Tue Jul 06, 2021 11:15 pm

Re: Monitor Mikrotik log by Telegram

Wed Jul 14, 2021 5:06 pm

doesn't work on CCR1036 , any new updates for this script. Please?
 
kivimart
newbie
Posts: 49
Joined: Thu Oct 10, 2013 3:06 pm

Re: Monitor Mikrotik log by Telegram

Thu Jul 15, 2021 9:02 pm

doesn't work on CCR1036 , any new updates for this script. Please?
Same on ccr-1009
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 7050
Joined: Tue Feb 25, 2014 12:49 pm
Location: Italy, but my Heart is in Україна

Re: Monitor Mikrotik log by Telegram

Fri Jul 16, 2021 2:46 am

Someone help the user, please.

I do not have telegram (and I do not want have it)

# LOG FILTER TO TELEGRAM
# BEGIN SETUP Edit Here
:local myserver ([/system identity get name])
:local scheduleName "LogFilter"
:local bot "941325023:AAH-pNTxLr021Av_C7bc9IGVdZDchDlwGb0"
:local ChatID "-262862011"
#Here you can specify which events from the logs you need to send.
:local startBuf [:toarray [/log find message~" failure" || message~"loop" || message~"critical" || message~"error" || message~"fcs" || message~"excessive"]]

# END SETUP

# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."

 /system scheduler add name=$scheduleName interval=300s start-date=Jul/09/2020 start-time=startup on-event=LogFilter

  /log warning "[LogFilter] Alert : Schedule created ."
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
 
# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
 
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
    
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." %0A%0A ".$message."\r\n")
   }

    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
  :if ($counter = ([:len $startBuf]-1)) do={
   :if ($keepOutput = false) do={    
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTimer." ".$message."\r\n")
      }
    }
  }
  :set counter ($counter + 1)
}

if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool fetch url="https://api.telegram.org/bot$bot/sendmessage\?chat_id=$ChatID&text=$myserver%0A%0A$output" keep-result=no;
}
 
User avatar
donsergio
Frequent Visitor
Frequent Visitor
Posts: 85
Joined: Wed Jan 31, 2018 8:35 pm
Location: Spain

Re: Monitor Mikrotik log by Telegram

Mon Aug 02, 2021 7:31 pm

Hi, I was long time working this script until upgrade ROS version that stop working.... I´m in stable 6.48.3

Anyone has checked in this ROS version?

Regards!!
 
rusinym
just joined
Posts: 1
Joined: Thu Aug 19, 2021 3:31 am

Re: Monitor Mikrotik log by Telegram

Thu Aug 19, 2021 3:42 am

Hi. I have the 6.45.9 version on my hAP-lite
I was wery interested in this monitor, so I made some fixes in code, and got success working masterpeace. Thanks to all !!!
You may find some bugs in code below
I apologize, but I wrote the code for the first time for the RouterOS
# BEGIN SETUP Edit Here
:local myserver ([/system identity get name])
:local scheduleName "LogFilter"
:local bot "YOUR_BOT_TOKEN"
:local ChatID "YOUR_CHANEL_ID"
:local startBuf [:toarray [/log find message~" failure" || message~"loop" || message~"down" || message~"fcs" || message~"excessive"]]
:local removeThese [:toarray ""]
# END SETUP

# warn if schedule does not exist and create it 
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."
  /system scheduler add name=$scheduleName interval=60s start-date=Jul/05/2019 start-time=startup on-event=LogFilter
  /log warning "[LogFilter] Alert : Schedule created ."
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
 
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
    
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message." %0A%0A ")
   }
    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
  :if ($counter = ([:len $startBuf])-1) do={
   :if ($keepOutput = false) do={    
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTime." ".$message)
      }
    }
  }
  :set counter ($counter + 1)
}
if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool fetch url="https://api.telegram.org/bot$bot/sendMessage\?chat_id=$ChatID&text=$myserver%0A%0A$output" keep-result=no;
}
 
smartlinkid
just joined
Posts: 1
Joined: Mon Aug 23, 2021 9:31 pm

Re: Monitor Mikrotik log by Telegram

Mon Aug 23, 2021 9:41 pm

thxs a lot of rusinym, for very nice fix this code, it's work very very very nice on crs board with ros 6.48.3, you are best :)
Hi. I have the 6.45.9 version on my hAP-lite
I was wery interested in this monitor, so I made some fixes in code, and got success working masterpeace. Thanks to all !!!
You may find some bugs in code below
I apologize, but I wrote the code for the first time for the RouterOS
# BEGIN SETUP Edit Here
:local myserver ([/system identity get name])
:local scheduleName "LogFilter"
:local bot "YOUR_BOT_TOKEN"
:local ChatID "YOUR_CHANEL_ID"
:local startBuf [:toarray [/log find message~" failure" || message~"loop" || message~"down" || message~"fcs" || message~"excessive"]]
:local removeThese [:toarray ""]
# END SETUP

# warn if schedule does not exist and create it 
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LogFilter] Alert : Schedule does not exist. Creating schedule ...."
  /system scheduler add name=$scheduleName interval=60s start-date=Jul/05/2019 start-time=startup on-event=LogFilter
  /log warning "[LogFilter] Alert : Schedule created ."
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
 
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
    
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message." %0A%0A ")
   }
    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
  :if ($counter = ([:len $startBuf])-1) do={
   :if ($keepOutput = false) do={    
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTime." ".$message)
      }
    }
  }
  :set counter ($counter + 1)
}
if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool fetch url="https://api.telegram.org/bot$bot/sendMessage\?chat_id=$ChatID&text=$myserver%0A%0A$output" keep-result=no;
}
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Thu Oct 07, 2021 5:35 pm

Hi All,
Please kindly some advice.
I found same script as OP however it is for email.
the script as follow (Email):
# BEGIN SETUP
#Change this to the name of your schedule (the date/time stamp is saved in the schedule's comment).
:local scheduleName "LogToEmail"

#Put your email address here.
:local emailAddress "XXXXXX"

#This currently detects two strings. It can be changed to more or less strings if desired. Remove: || message~"login failure" if you only want to use one string, or if you want more strings, add this same code at the end (but before the last two end brackets).
:local startBuf [:toarray [/log find topics~"system" || message~"logged" ]]

#Edit the quoted items for strings you want to be filtered out of the results. For example, if you want all "logged in" logs found, but you do not want any of the "logged in via telnet" logs included, simply include the word "telnet" in the array and these logs will be excluded. Double quote additional strings and separate them with semi-colons. If you don't want any logs filtered, simply declare the variable :local removeThese without any curly braces. curly braces sample as follow {"testing";"whatever string you want"}
:local removeThese 

# END SETUP
# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LOGMON] ERROR: Schedule does not exist. Create schedule and edit script to match name"
}
# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
# final output
:local output
:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}
:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   :set message [/log get $i message]
#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message."\r")
   }
#   if currentTime = lastTime, set keepOutput so any further logs found will be added to output
#   reset output in the case we have multiple identical date/time entries in a row as the last matching logs
#   otherwise, it would stop at the first found matching log, thus all following logs would be output
    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
#   if this is last log entry
  :if ($counter = ([:len $startBuf]-1)) do={
#   If keepOutput is still false after loop, this means lastTime has a value, but a matching currentTime was never found.
#   This can happen if 1) The router was rebooted and matching logs stored in memory were wiped, or 2) An item is added
#   to the removeThese array that then ignores the last log that determined the lastTime variable.
#   This resets the comment to nothing. The next run will be like the first time, and you will get all matching logs
   :if ($keepOutput = false) do={
#     if previous log was found, this will be our new lastTime entry      
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTime." ".$message."\r")
      }
    }
  }
  :set counter ($counter + 1)
}
# If we have output, save new date/time, and send email
if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool e-mail send to="$emailAddress" subject="MikroTik alert $currentTime" body="$output"
  /log info "[LOGMON] New logs found, send email"
}
#Other Notes, If you would rather run a script or whatever (instead of sending email), simply remove the email config line at the top, and change the "/tool email" line near the bottom to do whatever you want.
and i have modified it for telegram as follow:
# BEGIN SETUP
#Change this to the name of your schedule (the date/time stamp is saved in the schedule's comment).
:local scheduleName "LogToTelegram"

#put telegram ID
:local BotToken "XXXXXX";
:local ChatID "XXXXXX";
:local DeviceName [/system identity get name];

#This currently detects two strings. It can be changed to more or less strings if desired. Remove: || message~"login failure" if you only want to use one string, or if you want more strings, add this same code at the end (but before the last two end brackets).
:local startBuf [:toarray [/log find topics~"system" || message~"logged" ]]

#Edit the quoted items for strings you want to be filtered out of the results. For example, if you want all "logged in" logs found, but you do not want any of the "logged in via telnet" logs included, simply include the word "telnet" in the array and these logs will be excluded. Double quote additional strings and separate them with semi-colons. If you don't want any logs filtered, simply declare the variable :local removeThese without any curly braces. curly braces sample as follow {"testing";"whatever string you want"}
:local removeThese 

# END SETUP
# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[LOGMON] ERROR: Schedule does not exist. Create schedule and edit script to match name"
}
# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message
# final output
:local output
:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}
:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={
# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   :set message [/log get $i message]
#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message."\r")
   }
#   if currentTime = lastTime, set keepOutput so any further logs found will be added to output
#   reset output in the case we have multiple identical date/time entries in a row as the last matching logs
#   otherwise, it would stop at the first found matching log, thus all following logs would be output
    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }
#   if this is last log entry
  :if ($counter = ([:len $startBuf]-1)) do={
#   If keepOutput is still false after loop, this means lastTime has a value, but a matching currentTime was never found.
#   This can happen if 1) The router was rebooted and matching logs stored in memory were wiped, or 2) An item is added
#   to the removeThese array that then ignores the last log that determined the lastTime variable.
#   This resets the comment to nothing. The next run will be like the first time, and you will get all matching logs
   :if ($keepOutput = false) do={
#     if previous log was found, this will be our new lastTime entry      
     :if ([:len $message] > 0) do={
        :set output ($output.$currentTime." ".$message."\r")
      }
    }
  }
  :set counter ($counter + 1)
}
# If we have output, save new date/time, and send email
if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  /tool fetch url="https://api.telegram.org/bot$BotToken/sendMessage?chat_id=$ChatID&text=%E2%9D%97$DeviceName:$output" keep-result=no;
  /log info "[LOGMON] New logs found, send Telegram Message"
}
#Other Notes, If you would rather run a script or whatever (instead of sending email), simply remove the email config line at the top, and change the "/tool email" line near the bottom to do whatever you want.
But it doesn't work. i keep getting
"failure: closing connection: <400 Bad Request> 149.154.167.220:443 (4)"

but here's the strange part
if i were to lose the $ for the 'output' on the /tool fetch url such as below
 /tool fetch url="https://api.telegram.org/bot$BotToken/sendMessage\?chat_id=$ChatID&text=%E2%9D%97$DeviceName:output" keep-result=no;
the script runs, and able to send msg to telegram. but it is rather useless as i only receive "output"

anyone can help to spot what is issue with this ?
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Thu Oct 07, 2021 5:51 pm

Never mind
after comparing the email script with the OP script.

replace "\r" in this part :
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message."\r")
with "%0A%0A"
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output.$currentTime." ".$message."%0A%0A")
seems to do the trick.
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Fri Jan 14, 2022 6:18 am

Hi All,

anyone having issue with this script ?
after update to 6.49.2 the script now working intermittently.
it seems now when $output have too many lines, it somehow unable to send.
but if only consist 1 line, the script successfully sends to telegram.
is there a function to log the $output to a file ? i only able to save it in log and viewing the content in log is really difficult to ready (very long)

Thank you

This is a sample of msg to telegram that is successfully sent
%F0%9F%A4%96 <b>Homer:%0A</b> %F0%9F%8C%A1 <b>Temp = <i>34 %E2%84%83</i> </b> %0A %F0%9F%90%8F <b>Free Ram = <i>211 / 256 MB</i></b> %0A %E2%8F%B0 <b>Uptime = <i>21:11:22</i></b> %0A %E2%8C%9B <b>CPU = <i>2 % </i> </b>%0A%F0%9F%93%80 <b>Free Space = <i>4 / 16</i></b>

The others failed one as follow:
%0D%0A 17:56:49 - user XXXX logged out from 192.168.0.212 via winbox; %0D%0A 17:56:52 - user XXXX logged in from 192.168.0.212 via winbox;

i'm not sure what msg content on the below part that causes it to failed.
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Fri Jan 14, 2022 1:48 pm

after fiddling
with one of the script that is still working
:local DeviceName [/system identity get name];
:local systemTemp [:tonum [/system health get temperature]];
:local freemem ([/system resource get free-memory] / 1024 / 1024);
:local totmem ([/system resource get total-memory] / 1024 / 1024);
:local freehddspace ([/system resource get free-hdd-space] / 1024 / 1024);
:local totalhddspace ([/system resource get total-hdd-space] / 1024 / 1024);
:local cpuload ([/system resource get cpu-load]);
:local up ([/system resource get uptime]);

:local MessageText "%F0%9F%A4%96  <b>$DeviceName:%0A</b> %F0%9F%8C%A1  <b>Temp = <i>$systemTemp %E2%84%83</i> </b> %0A %F0%9F%90%8F  <b>Free Ram =  <i>$freemem / $totmem MB</i></b> %0A %E2%8F%B0  <b>Uptime = <i>$up</i></b> %0A %E2%8C%9B <b>CPU = <i>$cpuload % </i> </b>%0A%F0%9F%93%80  <b>Free Space = <i>$freehddspace / $totalhddspace</i></b> %0A%0A [b]howdy[/b]"

#get TGBotSenderScript to send
:local SendTelegramMessage [:parse [/system script  get TGBotSenderScript source]];
$SendTelegramMessage MessageText=$MessageText;
when add the word "howdy" it's ok, but if i change to "Howdy" the script is not sending.
which is odd.
is there something against capital H in mikrotik script ? but the strange thing is my device name is Homer and it is ok, although the placement is in front ($DeviceName).
 
User avatar
Jotne
Forum Guru
Forum Guru
Posts: 2838
Joined: Sat Dec 24, 2016 11:17 am
Location: Magrathean

Re: Monitor Mikrotik log by Telegram

Fri Jan 14, 2022 2:56 pm

Capital should work fine as in "Uptime"
 
Use Splunk> to log/monitor your MikroTik Router(s). See link below. :mrgreen:

MikroTik->Splunk
 
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Fri Jan 14, 2022 3:11 pm

Capital should work fine as in "Uptime"
yes I, agree, not sure why this is the case in the capital H.
i've changed the username with capital H to other name and the script now works again.
 
User avatar
eworm
Forum Veteran
Forum Veteran
Posts: 934
Joined: Wed Oct 22, 2014 9:23 am
Location: Oberhausen, Germany
Contact:

Re: Monitor Mikrotik log by Telegram

Sat Jan 15, 2022 12:42 pm

Looks like I have not yet shared the link to my scripts, no? You could try Forward log messages via notification.
You can configure the filters and it supports to send notifications via e-mail, Telegram and Matrix.
MTCNA # 2111NA7836 | MTCRE # 2202RE4756 | MTCTCE # 2202TCE5043
Manage RouterOS scripts and extend your devices' functionality: RouterOS Scripts
For contact join the RouterOS-Scripts Telegram group!
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Sun Jan 16, 2022 6:14 am

Looks like I have not yet shared the link to my scripts, no? You could try Forward log messages via notification.
You can configure the filters and it supports to send notifications via e-mail, Telegram and Matrix.
Thanks for this, will give it a read and try it.
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Mon Jan 24, 2022 1:32 pm

Capital should work fine as in "Uptime"
yes I, agree, not sure why this is the case in the capital H.
i've changed the username with capital H to other name and the script now works again.
just an update so I have another script to be called when sending telegram msg (credit to someone in the www) the script is as follow:
:local BotToken "XXXXX";
:local ChatID "XXXX";
:local ParseMode "html";
:local DisableWebPagePreview True;
:local SendText $MessageText;

:local tgUrl "https://api.telegram.org/bot$BotToken/sendMessage\?chat_id=$ChatID&text=$SendText&parse_mode=$ParseMode&disable_web_page_preview=$DisableWebPagePreview";

/tool fetch http-method=get url=$tgUrl output=none;
I remove the"&parse_mode=$ParseMode&disable_web_page_preview=$DisableWebPagePreview" and run the telegram msg status, and it will send to telegram chat id without html stuff. and then i re add the "&parse_mode=$ParseMode&disable_web_page_preview=$DisableWebPagePreview" and it works again. capital H or other stuff. so not sure what's the problem is but. if there is an odd issue with the HTML parse, but try to re run it without the parse and re try again.
 
dovydasz
just joined
Posts: 3
Joined: Fri Aug 03, 2018 2:06 pm

Re: Monitor Mikrotik log by Telegram

Fri Feb 11, 2022 11:53 am

Hello,

The script works (from katem07), I receive telegram messages immediately. But I receive the same messages again at 00:00 and 02:00 next day. Does anyone experience the same behaviors?
I'm on hAP ac^2, fw 6.49.2
 
kivimart
newbie
Posts: 49
Joined: Thu Oct 10, 2013 3:06 pm

Re: Monitor Mikrotik log by Telegram

Fri Feb 11, 2022 12:25 pm

Hello,

The script works (from katem07), I receive telegram messages immediately. But I receive the same messages again at 00:00 and 02:00 next day. Does anyone experience the same behaviors?
I'm on hAP ac^2, fw 6.49.2
I have the same issue.
 
User avatar
CyB3RMX
Member Candidate
Member Candidate
Posts: 144
Joined: Thu May 26, 2011 7:08 am

Re: Monitor Mikrotik log by Telegram

Sat Feb 12, 2022 3:38 am


is there something against capital H in mikrotik script ? but the strange thing is my device name is Homer and it is ok, although the placement is in front ($DeviceName).
I had a problem when the text to telegram started with a space then capital H, as " H" Telegram doesnt like that the text string starts with space for some reason. not sure if this helps.
Have a great day!
Certified: MTCNA - MTCWE - MTCRE
 
dermawas
newbie
Posts: 46
Joined: Sat Jul 10, 2021 7:06 am

Re: Monitor Mikrotik log by Telegram

Sat Feb 12, 2022 6:42 am


is there something against capital H in mikrotik script ? but the strange thing is my device name is Homer and it is ok, although the placement is in front ($DeviceName).
I had a problem when the text to telegram started with a space then capital H, as " H" Telegram doesnt like that the text string starts with space for some reason. not sure if this helps.
This is helpful, thanks a lot. to overcome the space i can give space before enclosing the capital H with <b> tag or italic. something like this:
"abcd <b>H</b> "
it's a workaround for now.
thanks again!
 
Whyred
just joined
Posts: 1
Joined: Fri Mar 25, 2022 9:30 am

Re: Monitor Mikrotik log by Telegram

Thu Mar 31, 2022 4:39 am



I had a problem when the text to telegram started with a space then capital H, as " H" Telegram doesnt like that the text string starts with space for some reason. not sure if this helps.
This is helpful, thanks a lot. to overcome the space i can give space before enclosing the capital H with <b> tag or italic. something like this:
"abcd <b>H</b> "
it's a workaround for now.
thanks again!
Can u share new script ?

Who is online

Users browsing this forum: No registered users and 11 guests