handling logging in laravel on balanced servers

Viewed 466

I have 2 balanced servers for my Laravel app, but each of them is logging in it's own target folder (we use a daily file logging): is there any way to have a centralized location to save logs to?

I already arranged the logging configurations to include server name in the output, but i can't figure out how to handle this situation.

Maybe an object storage? or what? Non third party solutions will be better, we would like to keep everything inside laravel and our servers, but if it's no choice we'll arrange an external solution.

1 Answers

Now there probably isn't a "best" way to do this and Laravel offers a lot of flexibility on how to do this if you check the docs. In fact since NewRelic is supported this can be a decent way to solve this issue if you are using NewRelic already.

We use the database to log. We can do this because the database is hosted outside the servers but in the same VPC of AWS which means the latency is very low. We have a table with id, message, detail, created_at, severity here's a simple way to do it:

In your EventServiceProvider (any service provider will work really)

Event::listen(MessageLogged::class, function (MessageLogged $messageLogged) {
      [ $level, $message, $context ] = [ $messageLogged->level, $messageLogged->message, $messageLogged->context ];
      if (!\Log::getLogger()->isHandling(Logger::toMonologLevel($level))) {
            return; // Don't log if the logger isn't actually handling this level
      }
      if (($message instanceof \Exception || $message instanceof \Throwable)) {
          $context = [$message];
          $message = $message->getMessage();
      }
      DB::table('log')->insert([
          'message' => $message
          'detail' => implode(PHP_EOL, $context ?: []),
          'created_at' => Carbon::now(),
          'severity' => $level
      ]);
});

If performance is an issue you can also create a task that will queue the processing of the log event, but that means you have to queue it with the time the event happened rather than the time it was handled.

Related