1. <?php
  2. /**
  3. * Generates log stream configurations for a legacy project based on a configuration file.
  4. *
  5. * @param string $configFilePath Path to the configuration file.
  6. * @return array An array of log stream configurations. Returns an empty array on error.
  7. */
  8. function generateLogStreamConfigs(string $configFilePath): array
  9. {
  10. if (!file_exists($configFilePath)) {
  11. error_log("Error: Configuration file not found: $configFilePath");
  12. return [];
  13. }
  14. $config = json_decode(file_get_contents($configFilePath), true);
  15. if ($config === null) {
  16. error_log("Error: Failed to decode JSON from configuration file: $configFilePath");
  17. return [];
  18. }
  19. $logStreamConfigs = [];
  20. if (isset($config['log_streams']) && is_array($config['log_streams'])) {
  21. foreach ($config['log_streams'] as $streamConfig) {
  22. if (is_array($streamConfig)) {
  23. $logStreamConfigs[] = [
  24. 'name' => $streamConfig['name'] ?? 'default', // Get stream name, default to 'default' if missing
  25. 'level' => $streamConfig['level'] ?? 'info', // Get log level, default to 'info'
  26. 'target' => $streamConfig['target'] ?? 'file', // Get target, default to 'file'
  27. 'file' => $streamConfig['file'] ?? null, // Path to file, can be null
  28. 'format' => $streamConfig['format'] ?? '%time %level %message%', //Log format
  29. 'max_size' => $streamConfig['max_size'] ?? 1024 * 1024, //Max file size in bytes
  30. 'max_files' => $streamConfig['max_files'] ?? 5, //Max number of files to rotate
  31. ];
  32. } else {
  33. error_log("Warning: Invalid log stream configuration found: " . json_encode($streamConfig));
  34. }
  35. }
  36. } else {
  37. error_log("Warning: 'log_streams' section not found or is not an array in config file: $configFilePath");
  38. }
  39. return $logStreamConfigs;
  40. }
  41. //Example usage:
  42. /*
  43. $configs = generateLogStreamConfigs('config.json');
  44. if (!empty($configs)) {
  45. echo "<pre>";
  46. print_r($configs);
  47. echo "</pre>";
  48. } else {
  49. echo "No log stream configurations generated.";
  50. }
  51. */
  52. ?>

Add your comment