ApplicationInsightsLog
extends BaseLog
in package
Sends CakePHP log events to Azure Application Insights.
Emits Application Insights-compatible trace telemetry either directly over HTTPS or through a local OpenTelemetry collector over OTLP/gRPC.
Table of Contents
Constants
- TELEMETRY_SCHEMA_VERSION : mixed = '1'
- MAX_MESSAGE_LENGTH : mixed = 32768
- MAX_PROPERTY_LENGTH : mixed = 8192
Properties
- $_defaultConfig : array<string, mixed>
- $buffer : array<int, array<string, mixed>>
- $droppedCount : int
- $endpoint : string
- $failCount : int
- $flushCount : int
- $instrumentationKey : string
- $otlpEnabled : bool
- $reportedSendFailure : bool
- $selfMetricsEmitted : bool
- $sendCount : int
- $sharedOtlpInstanceCount : int
- $sharedOtlpLogger : LoggerInterface|null
- $sharedOtlpLoggerProvider : LoggerProviderInterface|null
- $shutdownComplete : bool
- $totalFlushMs : float
- $usesSharedOtlpProvider : bool
Methods
- __construct() : mixed
- flush() : void
- Sends buffered telemetry to Application Insights.
- log() : void
- Sends a log message as Application Insights trace telemetry.
- shutdown() : void
- Shutdown hook: flush remaining telemetry then emit one self-metrics trace describing this process' exporter activity. Called via register_shutdown_function so the request response has already been sent under FPM (see flush()).
- buildPayload() : array<string, mixed>
- emitSelfMetrics() : void
- Emits a single trace describing the exporter's activity this process.
- failureMarkerPath() : string|null
- Returns the path to the file-backed suppression marker, or null when TMP is unavailable.
- failureRecentlyReported() : bool
- failureSuppressionKey() : string
- Returns the cache/marker key used for cross-process suppression.
- initializeOtlp() : void
- Configures an OTLP/gRPC logger that exports to the local Container Apps managed OpenTelemetry agent.
- markFailureReported() : void
- normalizeContext() : array<string, string>
- otelSeverity() : Severity
- Maps the legacy Application Insights severity scale to OpenTelemetry.
- parseConnectionString() : array<string, string>
- reportSendFailure() : void
- Reports one exporter failure per suppression window across the process.
- sampleRate() : float
- Reads the configured Application Insights sample rate.
- send() : bool
- Sends telemetry JSON through the configured transport.
- sendOtlp() : bool
- Sends a buffered Application Insights-compatible batch through OTLP.
- severityLevel() : int
- Maps PSR log levels to Application Insights severity levels.
- shouldSample() : bool
- Checks whether the current event should be sampled in.
- silenced() : mixed
- Runs a callable with PHP errors silenced. Used in place of `@` which PHPCS disallows in this codebase.
-
toOtlpRecord()
: Severity, level: string, attributes: array
} - truncate() : string
- Truncates telemetry fields to Application Insights-safe sizes.
Constants
TELEMETRY_SCHEMA_VERSION
public
mixed
TELEMETRY_SCHEMA_VERSION
= '1'
MAX_MESSAGE_LENGTH
private
mixed
MAX_MESSAGE_LENGTH
= 32768
MAX_PROPERTY_LENGTH
private
mixed
MAX_PROPERTY_LENGTH
= 8192
Properties
$_defaultConfig
protected
array<string, mixed>
$_defaultConfig
= [
'levels' => [],
'scopes' => [],
'formatter' => \Cake\Log\Formatter\DefaultFormatter::class,
'connectionString' => null,
'cloudRole' => 'kmp',
'cloudRoleInstance' => null,
'timeout' => 2.0,
'batchSize' => 25,
'sampleRate' => 100.0,
'channel' => 'application',
'transport' => null,
'otlpEndpoint' => null,
'otlpTimeout' => 0.05,
'otlpEmitter' => null,
// Suppress repeated send-failure log lines for this many seconds across
// every instance in the process. 0 disables suppression.
'failureSuppressSeconds' => 60,
// Optional callable that may rewrite/redact the interpolated message
// before it is buffered. Signature: function (string $message): string.
// Use this on channels that may contain PII (e.g. SQL queries).
'messageSanitizer' => null,
// When true, emit a single summary trace (channel=telemetry-health)
// during the shutdown flush so exporter overhead is observable.
'emitSelfMetrics' => true,
]
$buffer
private
array<int, array<string, mixed>>
$buffer
= []
$droppedCount
private
int
$droppedCount
= 0
$endpoint
private
string
$endpoint
$failCount
private
int
$failCount
= 0
$flushCount
private
int
$flushCount
= 0
$instrumentationKey
private
string
$instrumentationKey
$otlpEnabled
private
bool
$otlpEnabled
= false
$reportedSendFailure
private
bool
$reportedSendFailure
= false
$selfMetricsEmitted
private
bool
$selfMetricsEmitted
= false
$sendCount
private
int
$sendCount
= 0
$sharedOtlpInstanceCount
private
static int
$sharedOtlpInstanceCount
= 0
$sharedOtlpLogger
private
static LoggerInterface|null
$sharedOtlpLogger
= null
$sharedOtlpLoggerProvider
private
static LoggerProviderInterface|null
$sharedOtlpLoggerProvider
= null
$shutdownComplete
private
bool
$shutdownComplete
= false
$totalFlushMs
private
float
$totalFlushMs
= 0.0
$usesSharedOtlpProvider
private
bool
$usesSharedOtlpProvider
= false
Methods
__construct()
public
__construct([array<string, mixed> $config = [] ]) : mixed
Parameters
- $config : array<string, mixed> = []
-
Configuration array
flush()
Sends buffered telemetry to Application Insights.
public
flush() : void
Under PHP-FPM this attempts fastcgi_finish_request() first so the worker is released back to the pool before the HTTPS round-trip.
log()
Sends a log message as Application Insights trace telemetry.
public
log(mixed $level, Stringable|string $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
- $level : mixed
-
The severity level of the message being written
- $message : Stringable|string
-
The message to log
- $context : array<string|int, mixed> = []
-
Additional log context
shutdown()
Shutdown hook: flush remaining telemetry then emit one self-metrics trace describing this process' exporter activity. Called via register_shutdown_function so the request response has already been sent under FPM (see flush()).
public
shutdown() : void
buildPayload()
protected
buildPayload(string $level, string $message, array<string, mixed> $context) : array<string, mixed>
Parameters
- $level : string
- $message : string
- $context : array<string, mixed>
-
Additional log context
Return values
array<string, mixed>emitSelfMetrics()
Emits a single trace describing the exporter's activity this process.
private
emitSelfMetrics() : void
Bypasses sampling because it is already aggregated and infrequent.
failureMarkerPath()
Returns the path to the file-backed suppression marker, or null when TMP is unavailable.
private
failureMarkerPath(string $key) : string|null
Parameters
- $key : string
-
Cache key from failureSuppressionKey()
Return values
string|null —Absolute path or null when filesystem fallback is unavailable.
failureRecentlyReported()
private
failureRecentlyReported(int $window) : bool
Parameters
- $window : int
-
Suppression window in seconds
Return values
boolfailureSuppressionKey()
Returns the cache/marker key used for cross-process suppression.
private
failureSuppressionKey() : string
Return values
string —Cache key derived from the ingestion endpoint.
initializeOtlp()
Configures an OTLP/gRPC logger that exports to the local Container Apps managed OpenTelemetry agent.
private
initializeOtlp(string $endpoint) : void
Parameters
- $endpoint : string
markFailureReported()
private
markFailureReported(int $window) : void
Parameters
- $window : int
-
Suppression window in seconds (used for APCu TTL)
normalizeContext()
private
normalizeContext(array<string, mixed> $context) : array<string, string>
Parameters
- $context : array<string, mixed>
-
Additional log context
Return values
array<string, string>otelSeverity()
Maps the legacy Application Insights severity scale to OpenTelemetry.
private
otelSeverity(int $applicationInsightsSeverity) : Severity
Parameters
- $applicationInsightsSeverity : int
Return values
SeverityparseConnectionString()
private
parseConnectionString(string $connectionString) : array<string, string>
Parameters
- $connectionString : string
Return values
array<string, string>reportSendFailure()
Reports one exporter failure per suppression window across the process.
private
reportSendFailure(string $message) : void
Tries APCu first (process-wide for FPM workers in the same pool), then a small marker file in TMP keyed by the ingestion endpoint host, then falls back to per-instance suppression. error_log() output is always emitted at least once per window so operators still see failures.
Parameters
- $message : string
-
Failure message
sampleRate()
Reads the configured Application Insights sample rate.
private
sampleRate() : float
Return values
float —Sample percentage from 0 to 100
send()
Sends telemetry JSON through the configured transport.
private
send(string $json) : bool
Parameters
- $json : string
-
Encoded Application Insights envelope
Return values
bool —True when the request was accepted (2xx), false on any failure.
sendOtlp()
Sends a buffered Application Insights-compatible batch through OTLP.
private
sendOtlp(string $json) : bool
Parameters
- $json : string
Return values
boolseverityLevel()
Maps PSR log levels to Application Insights severity levels.
private
severityLevel(string $level) : int
Parameters
- $level : string
-
PSR log level
Return values
int —Application Insights severity level
shouldSample()
Checks whether the current event should be sampled in.
private
shouldSample() : bool
Return values
boolsilenced()
Runs a callable with PHP errors silenced. Used in place of `@` which PHPCS disallows in this codebase.
private
silenced(callable $fn) : mixed
Parameters
- $fn : callable
-
Operation to run
toOtlpRecord()
private
toOtlpRecord(array<string, mixed> $payload) : Severity, level: string, attributes: array}
Parameters
- $payload : array<string, mixed>
-
Application Insights envelope
Return values
Severity, level: string, attributes: arraytruncate()
Truncates telemetry fields to Application Insights-safe sizes.
private
truncate(string $value, int $maxLength) : string
Parameters
- $value : string
-
Telemetry field value
- $maxLength : int
-
Maximum allowed length
Return values
string —Truncated value