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

docs: integrate with log and others #5

Merged
merged 2 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
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
15 changes: 15 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,18 @@ windows-targets = { version = "0.52.6" }

[dev-dependencies]
names = { version = "0.14.0", default-features = false }

[[example]]
doc-scrape-examples = true
name = "tcp_sender"
path = "examples/tcp_sender.rs"

[[example]]
doc-scrape-examples = true
name = "udp_sender"
path = "examples/udp_sender.rs"

[[example]]
doc-scrape-examples = true
name = "unix_sender"
path = "examples/unix_sender.rs"
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,52 @@ Add `fasyslog` to your `Cargo.toml`:
cargo add fasyslog
```

```rust
use fasyslog::Severity;

fn main() {
let mut sender = fasyslog::sender::tcp_well_known().unwrap();
let message = format!("Hello, fasyslog!");
// send a message with RFC 3164 format
sender.send_rfc3164(Severity::ERROR, message).unwrap();
sender.flush().unwrap();

// send a message with RFC 5424 format
const EMPTY_MSGID: Option<&str> = None;
const EMPTY_STRUCTURED_DATA: Vec<fasyslog::SDElement> = Vec::new();
sender.send_rfc5424(Severity::ERROR, EMPTY_MSGID, EMPTY_STRUCTURED_DATA, message).unwrap();
sender.flush().unwrap();
}
```

If you'd like to integrate with `log` crate, you can try the `logforth` example:

```toml
[dependencies]
log = { version = "..." }
logforth = { version = "...", features = ["syslog"] }
```

```rust
use logforth::append::syslog;
use logforth::append::syslog::Syslog;
use logforth::append::syslog::SyslogWriter;

fn main() {
let syslog_writer = SyslogWriter::tcp_well_known().unwrap();
let (non_blocking, _guard) = syslog::non_blocking(syslog_writer).finish();

logforth::builder()
.dispatch(|d| {
d.filter(log::LevelFilter::Trace)
.append(Syslog::new(non_blocking))
})
.apply();

log::info!("This log will be written to syslog.");
}
```

## Example

Check the [examples](examples) directory for more examples.
Expand Down
8 changes: 8 additions & 0 deletions src/sender/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ impl SyslogSender {
}

/// Flush the underlying writer if needed.
///
/// When the underlying writer is a streaming writer (TCP, UnixStream, etc.), periodically
/// flush is essential to ensure that the message is sent to the syslog server [1].
///
/// When the underlying writer is a datagram writer (UDP, UnixDatagram, etc.), flush is a no-op,
/// and every call to `send_xxx` defines the boundary of the packet.
///
/// [1]: https://github.com/Geal/rust-syslog/issues/69
pub fn flush(&mut self) -> io::Result<()> {
match self {
SyslogSender::Tcp(sender) => sender.flush(),
Expand Down
16 changes: 12 additions & 4 deletions src/sender/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Cow;
use std::io;
use std::io::BufWriter;
use std::io::Write;
Expand Down Expand Up @@ -50,9 +51,7 @@ pub fn unix(path: impl AsRef<Path>) -> io::Result<SyslogSender> {

pub fn unix_well_known() -> io::Result<SyslogSender> {
cfg_if::cfg_if! {
if #[cfg(target_os = "linux")] {
unix("/dev/log")
} else if #[cfg(target_os = "macos")] {
if #[cfg(target_os = "macos")] {
// NOTE: This may not work on Monterey (12.x) and above,
// see also https://github.com/python/cpython/issues/91070.
unix("/var/run/syslog")
Expand Down Expand Up @@ -112,6 +111,7 @@ impl_syslog_sender_common!(UnixDatagramSender);
pub struct UnixStreamSender {
writer: BufWriter<UnixStream>,
context: SyslogContext,
postfix: Cow<'static, str>,
}

impl UnixStreamSender {
Expand All @@ -121,9 +121,17 @@ impl UnixStreamSender {
Ok(Self {
writer: BufWriter::new(socket),
context: SyslogContext::default(),
postfix: Cow::Borrowed("\r\n"),
})
}

/// Set the postfix when formatting Syslog message.
///
/// Default is "\r\n". You can use empty string to set no postfix.
pub fn set_postfix(&mut self, postfix: impl Into<Cow<'static, str>>) {
self.postfix = postfix.into();
}

/// Set the context when formatting Syslog message.
pub fn set_context(&mut self, context: SyslogContext) {
self.context = context;
Expand All @@ -137,7 +145,7 @@ impl UnixStreamSender {
/// Send a pre-formatted message.
pub fn send_formatted(&mut self, formatted: &[u8]) -> io::Result<()> {
self.writer.write_all(formatted)?;
self.writer.write_all(&[0; 1])?;
self.writer.write_all(self.postfix.as_bytes())?;
Ok(())
}

Expand Down