Skip to content

Commit

Permalink
Removed JSONL logger
Browse files Browse the repository at this point in the history
  • Loading branch information
follestad committed Nov 24, 2023
1 parent c381db1 commit faccf47
Show file tree
Hide file tree
Showing 4 changed files with 2 additions and 141 deletions.
17 changes: 2 additions & 15 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
CHANGELOG
=========

1.1.0
1.1.1
---
Added two helper functions:

```
saveExceptionToJsonL( Throwable $e, string $file_path ): void
```

Which accepts an exception and a path to a log file. The method will extract data from the exception and save this as a
JSON Line in the given file.

```
registerJsonl(string $file_path): void
```

Witch will simply add the `saveExceptionToJsonL` to the log que.
Removed JSONL as this should not belong to error handler.

1.0.1
---
Expand Down
51 changes: 0 additions & 51 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ $errorHandling->report( static function (\Throwable $e) {
# Show the exception to your user.
});

// Use the helper-function to log exceptions to a JSONL file.
$errorHandling->registerJsonl('/path/to/your/logfile.jsonl');

```

_There are basically no difference between the `log` and `report`. Log closures will be called first, then the
Expand Down Expand Up @@ -116,52 +113,4 @@ $errorHandling->report( function (\Throwable $e) {
die('MyCustomException was thrown');
}
} );
```

Helper function to store exceptions to JSON Line file.
---------------

The author of this component likes to log exceptions to JSONL and has therefore added two helper-functions for this.
These methods offer a streamlined approach for capturing and storing exception data in a structured, easily parsable
format. Use them if you'd like.

You can read more about JSON Line format here - https://www.atatus.com/glossary/jsonl/

#### Log uncaught exceptions to JSONL

```php
$errorHandler->registerJsonl('/path/to/your/logfile.jsonl');
```

The `registerJsonl` function is designed to simplify the process of logging uncaught exceptions to a JSON Lines (JSONL)
file. This function does two things. First it will try to create the directory where JSONL file is stored, or fail if
not
able to create the directory. Then it will register logging of uncaught errors with use of the
internal `saveExceptionToJsonL` method (see more below).

#### Store exception to JSONL file

```php
$errorHandler->saveExceptionToJsonL($exception, '/path/to/your/logfile.jsonl');
```

The `saveExceptionToJsonL` method is a utility function used by registerJsonl to log exceptions into a JSON Lines file.
This method is typically not called directly, but can be a great extension if you want to log exceptions that are
caught. Here's an example:

```php
# In your bootstrap file
function exception_log( \Throwable $e): ?int {
// Logic to create dir if not found...
return $errorHandler->saveExceptionToJsonL($e, EXCEPTION_LOG_JSONL );
}

# Somewhere in your app
try {
// Some implemented code
} catch( \Exception $e ) {
$line = exception_log($e) ?? 'NONE';
echo "Oops, something bad happened. Please contact support (Log ID: #$line)";
}

```
46 changes: 0 additions & 46 deletions src/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Closure;
use ErrorException;
use RuntimeException;
use Throwable;

class ErrorHandler {
Expand Down Expand Up @@ -122,49 +121,4 @@ public function report(Closure $closure, bool $reset = false): void {
$this->reportCallback[] = $closure;
}

/**
* Register exception logging to JSON Line file.
* A simple helper function to register all uncaught exceptions to a JSON Line file.
* Registers the saveExceptionToJsonL() function to log que.
*
* @param string $file_path Path to the JSON Lines file.
* @return void
* @throws RuntimeException If the directory for the JSON Lines file cannot be created.
*/
public function registerJsonl(string $file_path): void {
$dir = dirname( $file_path );
if( !is_dir( $dir ) && !mkdir( $dir, 0755, true ) && !is_dir( $dir ) ) {
throw new RuntimeException( sprintf( 'Jsonl Log directory "%s" was not created', $dir ) );
}
$this->log( fn(Throwable $e) => $this->saveExceptionToJsonL( $e, $file_path ) );
}

/**
* Saves an exception to a JSON Lines file.
* Logs exception details including timestamp, class, message, file, line, and request URI.
*
* @param Throwable $e The exception to log
* @param string $path Path to the JSONL file
* @return int|null Returns the line-number of which the log was added, or null if it failed to save log.
*/
public function saveExceptionToJsonL(Throwable $e, string $path): ?int {
try {
if( file_put_contents( $path, json_encode( [
'date' => date( 'Y-m-d H:i:s' ),
'class' => get_class( $e ),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'request_uri' => $_SERVER['REQUEST_URI'] ?? ''
], JSON_THROW_ON_ERROR ) . PHP_EOL, FILE_APPEND ) ) {
/** @phpstan-ignore-next-line */
return count( file( $path ) );
}
} catch( Throwable ) {
// Silence!
}
return null;
}


}
29 changes: 0 additions & 29 deletions tests/ErrorHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,35 +49,6 @@ public function testGeneratingLog(): void {
}


public function testLogToJsonl(): void {
// Assert that dir has been deleted if exist
$dir = __DIR__ . '/testDir/';
$file_path = $dir . 'test.jsonl';

// Delete the file if it exists.
if( is_file( $file_path ) && !unlink( $file_path ) ) {
throw new LogicException( "Failed to delete file: $file_path" );
}

// Attempt to remove the directory.
if( is_dir( $dir ) && !rmdir( $dir ) ) {
throw new LogicException( "Failed to delete directory: $dir" );
}

$this->assertDirectoryDoesNotExist( $dir );

// Register log
$errorHandler = new ErrorHandler();
$errorHandler->registerJsonl( $file_path );
// Make sure dir now exists
$this->assertDirectoryExists( $dir );
$testException = new \RuntimeException( "Test Exception" );
$errorHandler->handleException( $testException );
$this->assertFileExists( $file_path );
$content = file_get_contents( $file_path );
$this->assertStringContainsString( "Test Exception", $content );
}

public function testHandleError() {
$errorHandler = new ErrorHandler();
$this->expectException( \ErrorException::class );
Expand Down

0 comments on commit faccf47

Please sign in to comment.