20210212

The ultimate purge logs bash script for Laravel

Let's assume that you have a very large log table that can grow up to millions of records.

 In this example the table is named activity_logs and VERY IMPORTANT it should have an index in created_at to allow us to remove records by date.

If you put this shell script in the root folder of your Laravel project it will take the database credentials from your .env file and purgue the log table day by day, from an starting date to an end date (in the example from 6 months ago to 2 months ago)

#### Contents of purge_logs.sh

dbhost=$(grep -oP '^DB_HOST=\K.*' .env)
dbpass=$(grep -oP '^DB_PASSWORD=\K.*' .env)
dbname=$(grep -oP '^DB_DATABASE=\K.*' .env)
dbusername=$(grep -oP '^DB_USERNAME=\K.*' .env)

i=$(date --date="6 months ago" +"%Y-%m-%d")
limit=$(date --date="2 months ago" +"%Y-%m-%d")
while [ "$i" != "$limit" ]; do
    echo $i limit $limit
    tomorrow=$(date -I -d "$i + 1 day")

    mysql -u $dbusername -p$dbpass -h $dbhost --default-character-set=utf8 $dbname << EOF
delete from activity_logs
where
created_at>='$i'
and created_at<'$tomorrow'
EOF

    sleep 5
    i=$tomorrow
done

#### end of purge_logs.sh

Explanation

Those lines take the db parameters from the .env file and make them available to the script.

dbhost=$(grep -oP '^DB_HOST=\K.*' .env)
dbpass=$(grep -oP '^DB_PASSWORD=\K.*' .env)
dbname=$(grep -oP '^DB_DATABASE=\K.*' .env)
dbusername=$(grep -oP '^DB_USERNAME=\K.*' .env)

Then configure the starting date and the limit

i=$(date --date="6 months ago" +"%Y-%m-%d")
limit=$(date --date="2 months ago" +"%Y-%m-%d")

You can change the parameters as long as they are valid date params, for example you can use "today", "tomorrow", "2 weeks ago", ...

In the next two lines we'll start the loop and echo the dates for debug purposes, and guess the next day in the variable "tomorrow", beware, the limit should be greater than the start date, if you don't want an infinite loop :)

while [ "$i" != "$limit" ]; do
    echo $i limit $limit
    tomorrow=$(date -I -d "$i + 1 day")

 Then launch mysql with the script to delete the records between $i and $tomorrow

     mysql -u $dbusername -p$dbpass -h $dbhost --default-character-set=utf8 $dbname << EOF
delete from activity_logs
where
created_at>='$i'
and created_at<'$tomorrow'
EOF

 In the last lines we'll sleep for a while to avoid stressing our server and recalculate the $i date

    sleep 5
    i=$tomorrow
done

Finally you can add a line in your crontab to run the script once a day for example:

10 0 * * * cd root_folder; ./purge_logs.sh

Hope this help

 

20210101

Post resum 2020

Gadgets of the year (comprats o regalats):
Cap

Samarretes del any:
Ink Snorlax
Dark Star Summer Camp
LeChuck Grog
Offline Park
2020 bad review
psycho star wars
raise spirits up
I don’t always test my code but when I do, I do it in production
I am an engineer to save time, just assume I’m aleays right


Friky coses guays:
Stimulus
Sails.js
nedb
Redox
Tactician
inertia.js
svelte.dev
structurizr.com
strapi.io
dgraph.io
deno.land
https://www.biotech-foods.com
beekeeperstudio.io


Jocs als que m'he viciat aquest any:
Fallout Shellter
PUBG mobile
COD mobile

Grups guays que he descobert aquest any:
Bigott
Lisasinson
Crushed Beacks
Pet Shimmers
Alvvays
Comando Suzie
Soviet Soviet
Anabel lee
Topographies
Automatic
Chelsea Wolfe
Somos la herencia
Ambros Chapel
Luna y panorama de los insectos
Marcelo Criminal
Ela Minus
Décima víctima

Concerts als que he anat:
RIDE + Crushed Beaks
Sandy (Alex G) + Pet shimmers

Pelis que he vist:
Girl
The drug king
I’m not a serial killer
Toy Story 4
Captain Marvel
Thor el reino oscuro
Thor Ragnarok
Guardians of the galaxy
Guardians of the galaxy vol 2
Ant-man
Captain America winter soldier
Captain America Civil War
Time to hunt
Avengers Age of Ultron
Dr. Strange
Avengers Infinity War
Guns Akimbo
Grabbers
I love you, stupid
Rampant
The Clobberfield Paradox
Da 5 Bloods
Dolor y gloria
Velvet buzzsaw
Shin Godzilla
You were never really here
Mortal engines
Canino
The rules of attraction
Jupiter’s moon
1984
Greyhound
The old guard
Snowpiercer
Tiempo después
1917
System error
Extraterrestre
Outbreak
American Pickle
Illang la brigada del lobo
The wandering earth
#Alive
Aquaman
Take shelter
Showgirls
Borat 2
The Purge: Anarchy
Padre no hay más que uno
La caída del imperio Americano
La edad de la ignorancia
Please stand by
De Pollos y hombres
Old boy
On the rocks
Blade runner 2049
Dans la brume
Under the skin

Pelis vistes a Sitges:
The night
Vicious fun
La funeraria
Blackwater: Abyss
The pale door
Archenemy
Kubrick by Kubrick
Bumperkleef
Malnazidos
Lucky
Spirit walk
La vampira de Barcelona
Mandibules
The queen of black magic
Boys from country hell
No matarás
The old ways
Mosquito state
May the devil take you 2
She dies tomorrow
Tin Can
A perfect enemy
Le Nuee
Soul
Ghost in the shell
Snowden

Top 5 i bottom 5 Sitges:

Top 5 (de millor a pitjor):
Mandibules
Bumperkleef
Le Nuee
The queen of black magic
A perfect enemy

Bottom 5 (de millor a pitjor):
She dies tomorrow
Lucky
The pale door
La funeraria
Tin Can

Curts:
Cap

Llibres que he llegit:
Open, Andre Agassi
Sapiens
Historias de terror, Liz Phair
El consentimiento, Vanessa Sprinzora

Comics:
The Boys, tomos 1,2,3
Guardians of the galaxy vol1, vol2
Raven
Snowpiercer
X-Men la saga Messiah Complex


Series a les que m'he enganxat (per ordre d'adiccio):
Dracula
Watchmen
Star Trek TNG s5,s6,s7
Picard
Kingdom s2
The Mandalorian
Upload
The Last Dance
La conjura contra America
Silicon Valley s6
See
The Purge s1, s2
Snowpiercer
Community
Dietland
Utopia s1, s2
El colapso
Watchmen
El fin de la comedia
Seinfeld
Little Britain USA
Norsemen s1, s2
Pure
Dragonslayer666
Días de mierda
Patria
Utopia 2020 us
Star Trek Discovery s3
Euphoria
Parlement
The Terror s1
30 monedas

Teatre:
Berto, cuanta tontería

Documentals:
McMillions
One child nation
Jeffrey Epstein: Filthy rich
Polansky, se busca
Garbo, the spy
Catalunya Barcelona: La historia catalana de Barcelona
Deep water
Eugenio
Sesión Salvaje
El Palmar de Troya
You don’t Nomi
The forum
Too funny to fail
El desafio ETA
Banksters
Oeconomia
James May, our man in Japan
This giant beast that is global economy

Sortides al Extranjer:

Cap

Millors Hotels als que he anat:
Sa Tuna

Millors restaurants:
Gorria (2)
Xerta
Lluerna
Ferran Cerro
Direkte