is there any tools for tail the file by detect specific many keyword
Assistant
Yes, there are several tools and techniques you can use to tail a file and filter its output based on specific keywords. Here are some commonly used methods:
1. Using tail with grep:
The tail command can be combined with to filter lines that match specific keywords.
User
i have around 40 keywords
Assistant
User
tail -f filename.log | grep -Ei -f keywords.txt
correct it
Assistant
The command you provided is mostly correct for tailing a log file and filtering the output for keywords that are in a file. However, I would suggest a few minor adjustments for clarity and effectiveness:
Ensure that the keywords file (keywords.txt) is properly formatted. Each keyword should be on a new line without any extra whitespace.
Make sure to use the correct -E flag for extended regex if your keywords contain regex metacharacters. The -i flag makes the search case-insensitive.
Here's the corrected command with comments:
User
in windows
Assistant
To tail a log file and filter it using keywords on Windows, you can use several methods, including PowerShell and command-line findstr. Below are the approaches you can take:
User
@echo off
:loop
type filename.log | findstr /I /G:keywords.txt
timeout /t 1 > nul
goto loop
show me the example of result
Assistant
Let's assume you have a log file called filename.log and a keywords file called keywords.txt. Here's how everything would work, along with an example of what your output might look like when you execute the batch script.
'$keywords' is not recognized as an internal or external command,
operable program or batch file.
'Get-Content' is not recognized as an internal or external command,
operable program or batch file.
This provides a similar filtering capability as the grep solution.
3. Using multitail:
multitail is a specialized tool for monitoring log files. It allows you to view multiple log files in a single terminal and can filter based on patterns.
You can use sed for more advanced text processing if needed:
tail -f filename.log | sed -n '/keyword1/p; /keyword2/p; /keyword3/p'
5. Python Script:
If you need more flexibility in how you detect and process keywords, consider writing a simple Python script using tail functionality:
import time
def tail_f(filename, keywords):
with open(filename, 'r') as f:
f.seek(0, 2) # Move to the end of the file
while True:
line = f.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
if any(keyword in line for keyword in keywords):
print(line, end='')
keywords = ["keyword1", "keyword2", "keyword3"]
tail_f('filename.log', keywords)
6. Log Monitoring Tools:
There are also dedicated log monitoring tools like Logstash, Splunk, or Graylog that allow filtering and monitoring logs in real-time with user-friendly interfaces.
Conclusion
Choose the method that best suits your needs based on your environment and specific use cases. For quick command-line usage, tail with grep or awk will often be the simplest and most effective solution.
If you have around 40 keywords that you want to monitor in a log file, there are various efficient methods to do this. Here are a few options that can help you manage monitoring multiple keywords more effectively:
1. Using grep with Multiple Keywords:
You can pass multiple keywords to grep using a file or by constructing a regex pattern. Here’s a couple of ways to do it:
a. Using a Regex Pattern:
You can create a regex pattern that includes all your keywords separated by the pipe (|) character:
You would need to construct that large regex manually or generate it programmatically.
b. Using a File:
If your list of keywords is long (as in your case), it may be easier to save the keywords in a text file (e.g., keywords.txt), and use grep with the -f option to read them:
keywords.txt:
keyword1
keyword2
keyword3
...
keyword40
Then you can run:
tail -f filename.log | grep -f keywords.txt
2. Using awk:
Similar to grep, awk can also read from a file containing keywords:
awk 'NR==FNR{keywords[$1]; next} {for (kw in keywords) if ($0 ~ kw) print $0}' keywords.txt filename.log
3. Use sed:
sed can also be used similarly, but it's usually less straightforward for this type of operation.
4. Python Script:
For more flexibility in log processing and if the keywords list is extensive, using a Python script is highly advisable.
Python Example:
Here's a simple Python script that reads from a file and monitors for multiple keywords:
import time
def tail_f(filename, keywords):
with open(filename, 'r') as f:
f.seek(0, 2) # Move to the end of the file
while True:
line = f.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
if any(keyword in line for keyword in keywords):
print(line, end='')
# Load keywords from a text file
with open('keywords.txt', 'r') as kf:
keywords = [line.strip() for line in kf if line.strip()]
tail_f('filename.log', keywords)
5. Log Monitoring Tools:
If you're dealing with a complex environment or need more robust log management, consider using specialized log monitoring tools like Logstash, Splunk, or Graylog. These tools can index logs and provide powerful querying capabilities.
Conclusion:
For managing many keywords, using a dedicated keywords file is a clean approach, especially if you want to avoid complex command-line syntax. Python scripts provide additional flexibility if you need custom handling of log entries. Choose the method that best fits your workflow!
Correct Command
tail -f filename.log | grep -Ei -f keywords.txt
Breakdown:
tail -f filename.log: Continuously outputs new lines added to filename.log.
|: Pipes the output of tail to the next command.
grep -Ei -f keywords.txt:
-E: Enables extended regular expressions (useful if your keywords might include regex special characters).
-i: Makes the search case-insensitive.
-f keywords.txt: Reads the keywords from the specified file, allowing for multiple keyword matches.
Example of Use
Make sure that your keywords.txt file looks like this (one keyword per line):
error
warning
critical
failed
Additional Notes
If keywords.txt contains regular expressions, make sure all patterns are compatible with grep.
Also, if you want to see the line numbers or filenames in the output, you could add -n or -H respectively (though with tail, you typically don't need them).
If you encounter performance issues with grep, consider using pgrep or another tool like awk or sed if your filtering needs become more complex.
This command will effectively allow you to monitor any log file in real-time while filtering for the given set of keywords.
Method 1: Using PowerShell
You can use PowerShell's Get-Content to tail a file and filter it using an array of keywords.
Prepare your keywords:
Store your keywords in a text file (keywords.txt), with each keyword on a new line.
PowerShell Script:
Here’s how you can create a PowerShell command to achieve similar functionality:
Get-Content -Path 'filename.log' -Wait: Continuously watches the log file for new entries.
Where-Object { ... }: Filters each new line through the criteria inside the curly braces.
$line -match $_: Checks if the line matches any of the keywords.
Method 2: Using Command Prompt
If you're looking for a simpler command line option directly in the Command Prompt, you can use findstr. However, it's less flexible than PowerShell for multiple keywords.
Prepare your keywords:
Still have them in keywords.txt, and make sure they are formatted correctly.
Command Prompt Command:
Here's how you can use findstr:
@echo off
:loop
type filename.log | findstr /I /G:keywords.txt
timeout /t 1 > nul
goto loop
Breakdown:
type filename.log: Outputs the content of the log file.
findstr /I /G:keywords.txt:
/I: Makes the search case-insensitive.
/G:keywords.txt: Reads the search strings from the specified file.
timeout /t 1 > nul: Pauses for 1 second before re-checking the file.
goto loop: Re-executes the loop to check for new entries.
Method 3: Using Third-Party Tools
You can also consider using third-party tools like BareTail or LogExpert. These tools provide real-time monitoring of log files and often include filtering by keywords directly in the interface.
Conclusion
PowerShell offers a robust solution for tailing log files and filtering by multiple keywords in a Windows environment. The findstr command can be used for simpler cases, but for complex use, PowerShell is recommended.
Step 1: Sample Log File (filename.log)
Consider the following content in filename.log:
2023-10-01 12:00:00 Info: Starting process...
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:03:00 Info: Process completed successfully.
2023-10-01 12:04:00 Critical: System overload.
Step 2: Sample Keywords File (keywords.txt)
Your keywords.txt might contain:
error
warning
critical
Step 3: Batch Script
Below is the batch script you would run:
@echo off
:loop
type filename.log | findstr /I /G:keywords.txt
timeout /t 1 > nul
goto loop
Running the Script:
When you run this script, it will continuously check the contents of filename.log every second and filter the lines that contain any of the keywords specified in keywords.txt.
Example Output
If your filename.log contains new entries like the ones shown above, the output of the script would look like this:
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:04:00 Critical: System overload.
What Happens in the Background:
The script will start running and will first output all the lines that match the keywords from the log file.
If new lines are added to filename.log after the script starts, those new lines would typically not be shown again until they appear in the log file during a subsequent check (as buffered by the type command).
It performs a check every second (as per the timeout /t 1 command).
Notes:
Remember that type filename.log will print the entire content of the log file each time the loop runs, which can cause a performance issue with large log files. For tailing functionality that only shows new entries, consider using other methods or tools more suited for that purpose.
If you need more advanced features (like only printing new lines), PowerShell would be a better option (as discussed earlier) because it can handle real-time tailing of files more gracefully.
Certainly! Let's walk through how the PowerShell script will work with an example, including sample log content and the expected output.
Step 1: Sample Log File (filename.log)
Assume your filename.log contains the following lines:
2023-10-01 12:00:00 Info: Starting process...
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:03:00 Info: Process completed successfully.
2023-10-01 12:04:00 Critical: System overload.
Get-Content -Path 'keywords.txt': Reads the list of keywords from keywords.txt into the $keywords variable.
Get-Content -Path 'filename.log' -Wait: Continuously reads and waits for new content in filename.log.
Where-Object { ... }: Checks each line of the log to see if it matches any of the keywords.
Write-Output $line: If a match is found, it outputs the line.
Step 4: Example Output
When you run the script in PowerShell, the output would look something like this if the script is monitoring the log file in real-time and if the log content above is present:
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:04:00 Critical: System overload.
Real-Time Behavior
As new lines are added to filename.log that contain any of the keywords from keywords.txt, you would see those lines printed in real-time.
For example, if a new line 2023-10-01 12:05:00 Warning: CPU usage low. is added to the log, the output would immediately show:
2023-10-01 12:05:00 Warning: CPU usage low.
Notes:
Make sure to run this PowerShell script in a session with appropriate permissions to read the log file and keywords file.
This script is efficient for monitoring logs with varying content and can easily be adapted by changing the keyword file or log file as needed.
If you add more keywords to keywords.txt, they will automatically be included in the monitoring without altering the script.
The PowerShell script you provided is great for filtering log entries based on keywords, but if you want to achieve similar functionality using a batch script in CMD, you'll have to adjust the approach a bit since batch files do not have the same capabilities as PowerShell. Below is an equivalent batch script that achieves this functionality using findstr.
Step 1: Prepare Your Log and Keywords Files
Sample Log File (filename.log):
2023-10-01 12:00:00 Info: Starting process...
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:03:00 Info: Process completed successfully.
2023-10-01 12:04:00 Critical: System overload.
Sample Keywords File (keywords.txt):
error
warning
critical
Step 2: Create the Batch Script (tail_keywords.bat)
Here's a simple batch script that uses a loop to continuously check the log file for new lines that match any of the keywords in keywords.txt:
@echo off
setlocal enabledelayedexpansion
:: Clear the screen
cls
:loop
:: Read the current contents of the log file
:: Redirect stdout to a temporary file, so we can check it later
type filename.log > temp_log.txt
:: Loop through each keyword in keywords.txt
for /f "usebackq delims=" %%k in ("keywords.txt") do (
echo Checking for keyword: %%k
findstr /I "%%k" temp_log.txt
)
:: Wait for a second before checking again
timeout /t 1 /nobreak > nul
:: Go back to the start of the loop
goto loop
Breakdown of the Batch Script:
@echo off: Prevents commands from being printed to the console.
setlocal enabledelayedexpansion: Enables the use of delayed environment variable expansion.
cls: Clears the command window.
:loop: A label that marks the beginning of the loop.
type filename.log > temp_log.txt: Reads the contents of filename.log into a temporary file, temp_log.txt.
for /f "usebackq delims=" %%k in ("keywords.txt") do (...): Loops through each line in keywords.txt and assigns it to the variable %%k.
findstr /I "%%k" temp_log.txt: Searches for each keyword in the temporary log file.
timeout /t 1 /nobreak > nul: Waits for 1 second before re-checking the log file.
goto loop: Goes back to the start of the loop.
Execution
Save the batch script in a file named tail_keywords.bat.
Place the script in the same directory as filename.log and keywords.txt.
Open a Command Prompt and navigate to the directory where your batch file is located.
Run the script by typing tail_keywords.bat.
Example Output
When you run the batch script, you will see output similar to this when matches are found:
Checking for keyword: error
2023-10-01 12:02:00 Error: Failed to connect to server.
Checking for keyword: warning
2023-10-01 12:01:00 Warning: Disk usage high.
Checking for keyword: critical
2023-10-01 12:04:00 Critical: System overload.
Notes:
This script simply checks the entire log file each time. If you're looking for performance improvements or efficiency when dealing with large log files, consider using PowerShell or a dedicated log monitoring tool.
The batch script will print the matched lines every time it checks, so you may see repeated matches if lines do not change. Adjust the script as necessary depending on your needs.
If you want to run a PowerShell script directly from a batch file (.bat), you can invoke PowerShell within the batch script. Here’s how to create a .bat file that runs your PowerShell code.
Step 1: Create the Batch Script (run_power_shell.bat)
Here’s how you can do this:
@echo off
:: Running a PowerShell script from a batch file
powershell -Command "
$keywords = Get-Content -Path 'keywords.txt'
Get-Content -Path 'filename.log' -Wait | Where-Object {
$line = $_
$keywords | ForEach-Object {
if ($line -match $_) {
Write-Output $line
}
}
}
"
Explanation:
@echo off: This prevents the commands from being displayed in the command prompt.
powershell -Command: This is how you invoke PowerShell from a batch file.
The entire PowerShell script is enclosed in double quotes.
The line Write-Output $line will output matching lines to the console.
Step 2: Preparing Your Files
Make sure that:
You have a filename.log file with log entries.
You have a keywords.txt file with keywords listed, one per line.
Example Log File (filename.log):
2023-10-01 12:00:00 Info: Starting process...
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:03:00 Info: Process completed successfully.
2023-10-01 12:04:00 Critical: System overload.
Example Keywords File (keywords.txt):
error
warning
critical
Step 3: Execution
Save the batch script as run_power_shell.bat.
Ensure the filename.log and keywords.txt files are in the same directory as the batch file (or adjust paths accordingly).
Open Command Prompt and navigate to the directory where your batch file is located.
Run the script by typing run_power_shell.bat.
Expected Output
When you execute the batch file, you should see output similar to this:
2023-10-01 12:01:00 Warning: Disk usage high.
2023-10-01 12:02:00 Error: Failed to connect to server.
2023-10-01 12:04:00 Critical: System overload.
Notes:
This method effectively allows you to run your original PowerShell script from within a batch file.
Ensure PowerShell's execution policy permits running scripts if you encounter any restrictions. You might need to run Set-ExecutionPolicy RemoteSigned in an elevated PowerShell console if you're hitting execution policy issues.
This batch script will run the PowerShell command and display the output in the command prompt, continuously checking the log file for matches based on the keywords provided.
To play a sound notification using ffplay in your PowerShell script (invoked from a batch file), you'll first need to ensure you have ffmpeg installed, as ffplay is part of the ffmpeg suite of tools.
Here’s an updated version of the batch file that plays a sound when a keyword matches. You can use a sound file of your choice (e.g., notify.wav).
Step 1: Prepare Your Files
Make sure you have ffmpeg installed and accessible from your command line. You can download it from the official FFmpeg website.
Create or choose a sound file (e.g., notify.wav) that you want to play for notifications.
Step 2: Create or Update the Batch Script (run_power_shell.bat)
Here’s the updated batch script to include sound notifications:
@echo off
:: Path to your sound file
set "soundFile=notify.wav"
:: Running a PowerShell script from a batch file
powershell -Command "
$keywords = Get-Content -Path 'keywords.txt'
Get-Content -Path 'filename.log' -Wait | Where-Object {
$line = $_
$keywords | ForEach-Object {
if ($line -match $_) {
Write-Output $line
Start-Sleep -Milliseconds 500 # Optional: Wait a moment before playing the sound
Start-Process -NoNewWindow -FilePath 'ffplay' -ArgumentList '-nodisp', '-autoexit', '$env:soundFile'
}
}
}
"
Explanation of the Additions:
set "soundFile=notify.wav": Specifies the path to the sound file you want to play. Ensure it's accessible or provide the full path.
Start-Process -NoNewWindow -FilePath 'ffplay' -ArgumentList '-nodisp', '-autoexit', '$env:soundFile': This starts ffplay to play the sound file. -nodisp prevents a video window from opening, and -autoexit will close ffplay after the sound finishes playing.
Step 3: Make Sure All Files Are Correctly Placed
filename.log: Ensure this file contains the logs you want to monitor.
keywords.txt: Ensure this file contains the relevant keywords.
notify.wav: Place the sound file in the same directory, or update the path in the script.
Step 4: Execution
Save the batch script after making changes.
Open a Command Prompt and navigate to the directory where your batch file is located.
Run the script by typing run_power_shell.bat.
Expected Behavior
The script will monitor filename.log.
When a line containing any of the keywords from keywords.txt is found, that line will be printed in the Command Prompt.
A notification sound will play each time a match is detected.
Notes
Make sure FFmpeg is properly installed and that the path to ffplay is included in your system's PATH variable, or use the full path to ffplay.exe in the batch script.
Adjust the path to the sound file if it's not in the same directory.
Test the script with lines in your log file that contain the keywords to ensure everything works as expected.
To set up the batch script so that it plays a corresponding .wav file whose name matches the keyword found in the log file (with spaces in the keyword), you can use a combination of string manipulation in PowerShell.
Updated Batch Script (run_power_shell.bat)
Here's how to update your batch script to play a .wav file with the filename based on the matching keyword, including spaces in the keyword:
@echo off
:: Running a PowerShell script from a batch file
powershell -Command "
$keywords = Get-Content -Path 'keywords.txt'
Get-Content -Path 'filename.log' -Wait | Where-Object {
$line = $_
$keywords | ForEach-Object {
if ($line -match $_) {
Write-Output $line
$soundFile = \"$_`.wav\" # Create the sound file name based on the matched keyword
Start-Sleep -Milliseconds 500 # Optional: Wait a moment before playing the sound
Start-Process -NoNewWindow -FilePath 'ffplay' -ArgumentList '-nodisp', '-autoexit', $soundFile
}
}
}
"
Explanation of Changes:
**$soundFile = \"$_.wav"**: This line constructs the name of the .wavfile corresponding to the matched keyword. If the keyword is"START MON_MEM", then it will look for a file named START MON_MEM.wav`.
Note on Escape Characters: In PowerShell, the backtick () is the escape character, and using it before .wav` ensures that PowerShell correctly interprets it as part of the string.
Example Keywords File (keywords.txt)
Make sure your keywords.txt file looks like this with keywords that can include spaces:
START MON_MEM
Memory Leak Detected
Disk Space Low
Example Log File (filename.log)
Here’s a sample log file:
2023-10-01 12:00:00 Info: Starting process for START MON_MEM...
2023-10-01 12:01:00 Warning: Disk space low warning triggered.
2023-10-01 12:02:00 Error: Memory leak detected at runtime.
2023-10-01 12:03:00 Info: Process completed successfully.
Step 4: Make Sure All Files Are Correctly Placed
The sound files should be named exactly as the keywords (with spaces included) and saved with a .wav extension in the same directory as your batch file.
For example: START MON_MEM.wav, Memory Leak Detected.wav, Disk Space Low.wav.
Ensure that both filename.log and keywords.txt are set up as described earlier.
Step 5: Execution
Save the updated batch script as run_power_shell.bat.
Open Command Prompt and navigate to the directory where your batch file is located.
Run the script by typing run_power_shell.bat.
Expected Behavior:
When the script finds a line in filename.log that matches a keyword from keywords.txt, it will print the line to the console.
It will attempt to play the corresponding .wav sound using ffplay.
Notes:
Ensure that the .wav files are named correctly and that they exist in the specified directory.
If you're still having issues with path names or spaces in the file names, you may need to carefully check that they match exactly, including capitalization.
Ensure ffmpeg and ffplay are installed and accessible in your environment. If not, you must provide the full path to ffplay.exe in the batch script.
2023-10-01 12:00:00 Info: Starting process for START MON_MEM...
2023-10-01 12:01:00 Warning: Disk space low warning triggered.
2023-10-01 12:02:00 Error: Memory leak detected at runtime.
2023-10-01 12:03:00 Info: Process completed successfully.
2023-10-01 12:00:00 Info: Starting process for START MON_MEM...
2023-10-01 12:01:00 Warning: Disk space low warning triggered.
2023-10-01 12:02:00 Error: Memory leak detected at runtime.
2023-10-01 12:03:00 Info: Process completed successfully.
แน่นอนครับ! ถ้าคุณไม่แน่ใจว่า ffplay จะทำงานบนเครื่อง PC ของคุณ คุณสามารถใช้ VLC Media Player แทนได้ เนื่องจากมันเป็นเครื่องมือที่ได้รับความนิยมและสามารถเล่นไฟล์เสียงได้ง่าย
ขั้นตอนที่ 1: ติดตั้ง VLC
ถ้าคุณยังไม่ได้ติดตั้ง VLC Media Player คุณสามารถดาวน์โหลดและติดตั้งได้จาก เว็บไซต์เถ้าแก่ VLC.
Sure! Below is a Python script that functions similarly to your original PowerShell script. It will monitor a log file in real-time for specific keywords and play a corresponding audio file if a keyword match is found.
Prerequisites
Python Installation: Ensure that Python is installed on your system. You can download it from python.org.
Required Libraries: You will need the playsound library for playing sounds. You can install it via pip if you haven't already:
import time
import os
from playsound import playsound
# Define paths
keywords_file = 'keywords.txt'
log_file = 'filename.log'
sound_dir = 'sound/'
# Load keywords from file
def load_keywords(filepath):
with open(filepath, 'r') as file:
return [line.strip() for line in file]
# Tail the log file
def tail_f(filename):
with open(filename, 'r') as f:
f.seek(0) # Move to the end of the file
while True:
line = f.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
yield line
# Play sound if keyword is found
def play_sound_for_keywords(keywords, line):
for keyword in keywords:
if keyword in line:
print(f"Keyword found: {keyword} -> {line.strip()}")
sound_file = os.path.join(sound_dir, f"{keyword}.mp3")
if os.path.exists(sound_file):
playsound(sound_file)
else:
print(f"Sound file not found: {sound_file}")
def main():
keywords = load_keywords(keywords_file)
print("Monitoring log file for keywords...")
for line in tail_f(log_file):
play_sound_for_keywords(keywords, line)
if __name__ == "__main__":
main()
Explanation of the Script:
Load Keywords: The script reads the keywords from keywords.txt.
Tail the Log File: The tail_f function simulates the tail command by reading new lines from filename.log as they are added.
Check for Keywords: The play_sound_for_keywords function checks if any of the keywords are present in the current line of the log file. If a match is found, it tries to play the corresponding sound file.
Play Sound: The playsound function from the playsound library is used to play the sound file located in the sound/ directory based on the keyword matched. If the sound file does not exist, it will print a warning message.
Main Loop: The main function coordinates the loading of keywords and monitoring the log file in a continuous loop.
Running the Script
Save the script code in a file named monitor_alert.py.
Ensure all necessary files (keywords, log file, and sound files) are properly placed in the corresponding directories.
Open a terminal and navigate to the directory where monitor_alert.py is located.
Run the script:
python monitor_alert.py
Expected Behavior
The script will continuously monitor filename.log.
When a line containing any of the keywords from keywords.txt is detected, it will print that line to the console and play the corresponding sound file from the sound/ directory.
If you have any further questions or need help with any adjustments, feel free to ask!
การตรวจสอบคำหลัก:
หากไม่มีบรรทัดใหม่ if not line: จะทำการหยุดชั่วคราว (time.sleep(0.1)) และเช็คอีกครั้งในลูป
import time
import os
from playsound import playsound
# Define paths
keywords_file = 'keywords.txt'
log_file = 'filename.log'
sound_dir = 'sound/'
# Load keywords from file
def load_keywords(filepath):
with open(filepath, 'r') as file:
return [line.strip() for line in file]
# Tail the log file
def tail_f(filename):
with open(filename, 'r') as f:
# Read existing lines to check for keywords
lines = f.readlines()
for line in lines:
yield line
f.seek(0) # Move to the end of the file for new lines
while True:
line = f.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
yield line
# Play sound if keyword is found
def play_sound_for_keywords(keywords, line):
for keyword in keywords:
if keyword in line:
print(f"Keyword found: {keyword} -> {line.strip()}")
sound_file = os.path.join(sound_dir, f"{keyword}.mp3")
if os.path.exists(sound_file):
playsound(sound_file)
else:
print(f"Sound file not found: {sound_file}")
def main():
keywords = load_keywords(keywords_file)
print("Monitoring log file for keywords...")
for line in tail_f(log_file):
play_sound_for_keywords(keywords, line)
if __name__ == "__main__":
main()