1个不稳定版本
0.1.0 | 2023年7月24日 |
---|
#1741 in 编码
34KB
830 行
alogfmt
使用serde实现logfmt编码器。
要使用,请将以下表格添加到您的Cargo.toml
中的[dependencies]
。
alogfmt = "^0.1.0"
用法
该包的主要接口由to_string
、to_bytes
和to_writer
函数组成。这些函数可以将logfmt编码的结构序列化为String
、Vec<u8>
和一个io::Write
。
use alogfmt::{to_string, to_bytes, to_writer};
use anyhow::Result;
use serde::Serialize;
#[derive(Serialize)]
struct MyStruct {
pub ts: u64,
pub message: String,
}
fn main() -> Result<()> {
let s = MyStruct{
ts: 1690232215,
message: String::from("Hello World!"),
};
let lf = to_string(&s)?;
assert_eq!(
lf,
r#"ts=1690232215 message="Hello World!""#
);
Ok(())
}
也导出了Serializer
实现。它包装了一个io::Write
,可以像to_writer
一样使用。由于Serializer
的构造并不特别昂贵,因此通常调用to_writer
应该没问题。如果您想重用Serializer
,您必须调用serializer.reset()
或serializer.next()
来重置序列化器的内部状态,使其准备好下一个文档。
use alogfmt::Serializer;
use anyhow::Result;
use serde::Serialize;
#[derive(Serialize)]
struct MyStruct {
pub ts: u64,
pub message: String,
}
fn main() -> Result<()> {
let s = MyStruct{
ts: 1690232215,
message: String::from("Hello World!"),
};
let mut serializer = Serializer::new(Vec::new());
for i in 0..3 {
s.serialize(&mut serializer)?;
serializer.next()?;
}
// take back the io::Write so we can check the results
let result = unsafe {
// The serializer should only ever produce valid utf8, so
// we can use from_utf8_unchecked to avoid the overhead of
// checking if the vector is UTF-8 encoded, though the safe
// from_utf8 would work just as well.
String::from_utf8_unchecked(serializer.writer())
};
assert_eq!(
result,
"ts=1690232215 message=\"Hello World!\"\nts=1690232215 message=\"Hello World!\"\nts=1690232215 message=\"Hello World!\"\n"
);
Ok(())
}
许可证
Copyright (C) 2023 Aurora McGinnis
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
依赖关系
~0.5–1MB
~24K SLoC