Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Codable extension for Logger.MetadataValue #334

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Sources/Logging/MetadataProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,63 @@ extension Logger.MetadataProvider {
}
}
}


extension Logger.MetadataValue: Codable {
private enum CodingKeys: String, CodingKey {
case type
case value
}

private enum ValueType: String, Codable {
case string
case stringConvertible
case dictionary
case array
}

public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)

switch self {
case .string(let stringValue):
try container.encode(ValueType.string, forKey: .type)
try container.encode(stringValue, forKey: .value)

case .stringConvertible(let customValue):
try container.encode(ValueType.stringConvertible, forKey: .type)
try container.encode(customValue.description, forKey: .value) // Encode description

case .dictionary(let dictValue):
try container.encode(ValueType.dictionary, forKey: .type)
try container.encode(dictValue, forKey: .value)

case .array(let arrayValue):
try container.encode(ValueType.array, forKey: .type)
try container.encode(arrayValue, forKey: .value)
}
}

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(ValueType.self, forKey: .type)

switch type {
case .string:
let stringValue = try container.decode(String.self, forKey: .value)
self = .string(stringValue)

case .stringConvertible:
let stringValue = try container.decode(String.self, forKey: .value)
self = .stringConvertible(stringValue) // Store as `stringConvertible` using `String` type

case .dictionary:
let dictValue = try container.decode(Logger.Metadata.self, forKey: .value)
self = .dictionary(dictValue)

case .array:
let arrayValue = try container.decode([Logger.MetadataValue].self, forKey: .value)
self = .array(arrayValue)
}
}
}
Loading