Truncate the home-assistant.log file Using a Shell Command
- A command_line sensor to monitor the home-assistant.log file size
- A shell_command to truncate the log file to 100MB
- An automation to execute the shell command when the file grows to 200MB
File Size Sensor
Creating a sensor to monitor the size of the log file is pretty straightforward. Although there is a file_size sensor I went with a command_line sensor because it was easier to test and debug using the Reload Command Line Entities button in the Server Controls panel. This is the YAML code I used to get the file size in megabytes in my configuration.yaml file:
# https://joshmccarty.com/truncate-the-home-assistant-log-file-using-a-shell-command/
# change to as flow
# https://www.home-assistant.io/integrations/command_line/
command_line:
- sensor:
name: "Ha Log File Size"
command: "du -m home-assistant.log | cut -f1"
unit_of_measurement: MB
value_template: "{{ value|int(0) }}"
scan_interval: 3600 Shell Command
The shell_command to truncate the log file size took a some trial and error. Ultimately I created a bash script file that the shell_command executed so I could make changes to the script without restarting Home Assistant every time I wanted to try a different shell command to get things working right.
I created the shell script file using the Visual Studio Code Add-on, but you could do this however you edit YAML files in your current Home Assistant instance. I named it truncate_log.sh and saved it in the config folder for Home Assistant. The file contains the following script:
#!/usr/bin/env sh
truncate -s 100MB /config/home-assistant.log Once the shell script file is created, you have to make it executable using the following command in the config directory: chmod +x truncate_log.sh. I did this via the Terminal/SSH Add-on. Then you can create the shell_command to call the bash script file in your configuration.yaml file:
shell_command:
truncate_log: /config/truncate_log.sh Automating Things
Finally, I created an automation that uses a numeric_state trigger to run the shell_command when the log file gets over 200MB in size. I did this via the UI, but the following YAML will work:
alias: 'Truncate Log File'
description: >-
This truncates the home-assistant.log file to 100MB when it grows past 200MB
to prevent it from ballooning in size between restarts.
trigger:
- platform: numeric_state
entity_id: sensor.log_file_size
above: '200'
for:
hours: 0
minutes: 10
seconds: 0
milliseconds: 0
action:
- service: shell_command.truncate_log
mode: single
Comments
Be the first to post a comment