Skip to content

Commit

Permalink
Fix fields length for serializing record struct in JsonFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
SpriteOvO committed Aug 20, 2024
1 parent 813edaf commit adf6c0d
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions spdlog/src/formatter/json_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@ use crate::{
Error, Record, StringBuf, __EOL,
};

fn opt_to_num<T>(opt: Option<T>) -> usize {
opt.map_or(0, |_| 1)
}

struct JsonRecord<'a>(&'a Record<'a>);

impl<'a> Serialize for JsonRecord<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let src_loc = self.0.source_location();

let mut record =
serializer.serialize_struct("JsonRecord", if src_loc.is_none() { 4 } else { 5 })?;
let fields_len =
4 + opt_to_num(self.0.logger_name()) + opt_to_num(self.0.source_location());
let mut record = serializer.serialize_struct("JsonRecord", fields_len)?;

record.serialize_field("level", &self.0.level())?;
record.serialize_field(
Expand All @@ -41,7 +44,7 @@ impl<'a> Serialize for JsonRecord<'a> {
record.serialize_field("logger", logger_name)?;
}
record.serialize_field("tid", &self.0.tid())?;
if let Some(src_loc) = src_loc {
if let Some(src_loc) = self.0.source_location() {
record.serialize_field("source", src_loc)?;
}

Expand Down

0 comments on commit adf6c0d

Please sign in to comment.