Skip to content

Commit

Permalink
Fix printing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ogesaku committed Jan 2, 2024
1 parent 193aead commit 1f2993f
Show file tree
Hide file tree
Showing 22 changed files with 384 additions and 70 deletions.
21 changes: 16 additions & 5 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,45 @@
# Contributing

## Commit messages

Before writing a commit message read [this article](https://chris.beams.io/posts/git-commit/).

## Build

Before pushing any changes make sure project builds without errors with:

```
./gradlew build
```

## Unit tests

This project uses [Kotest](https://kotest.io/) for testing.

- please use the `Spec` suffix for new test classes
- make sure tests clearly document new feature

## Validate changes locally

Before submitting a pull request test your changes locally on a sample project.
There are few ways for local testing:

- simply use one of the [sample subprojects](https://github.com/coditory/klog/tree/master/samples)
- or publish library to maven local repository with `./gradlew publishToMavenLocal` and use it in any project
via [`mavenLocal()`](https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:maven_local) repository

## Documentation
## Validating with snapshot release
Snapshot release is triggered automatically after merge to the main branch.
To use a released snapshot version make sure to register Sonatype snapshot repository in gradle with:

```
// build.gradle.kts
repositories {
mavenCentral()
maven {
url = URI("https://oss.sonatype.org/content/repositories/snapshots")
}
}
```

The snapshot version can be found in GitHub Action build log.

## Documentation
If change adds new feature or modifies a new one
update [documentation](https://github.com/coditory/klog/tree/master/samples).
38 changes: 19 additions & 19 deletions .github/ISSUE_TEMPLATE/bug-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@ name: Bug report
about: Reporting bugs and other issues
labels: bug
---
<!-- The bug you're experiencing might have already be reported! -->
<!-- Please search in the [issues](https://github.com/coditory/sherlock-distributed-lock/issues) before creating one. -->

## Context
<!-- How has this issue affected you? What are you trying to accomplish? -->
<!-- Providing context helps us come up with a solution that is most useful in the real world -->
<!-- The bug you're experiencing might have already be reported. -->
<!-- Please search in the [issues](https://github.com/coditory/sherlock-distributed-lock/issues) before creating one. -->

## Expected Behavior
<!-- Tell us what should happen -->
## Context
<!-- How has this issue affected you? What are you trying to accomplish? -->
<!-- Providing context can help find a solution that is most useful. -->

## Observed Behavior
<!-- Tell us what happens instead of the expected behavior -->
## Expected Behavior
<!-- What should happen? -->

## Steps to Reproduce
<!-- Provide a link to a live example, or an unambiguous set of steps to -->
<!-- reproduce this bug. Include code to reproduce, if relevant -->
## Observed Behavior
<!-- What happens instead of the expected behavior? -->

## Your Environment
<!-- Include as many relevant details about the environment you experienced the bug in -->
* Library version:
* Java (and/or Kotlin) version:
* Gradle version:
* Gradle scan link (add `--scan` option when running the gradle task):
* Link to your project (if it's a public repository):
## Steps to Reproduce
<!-- Provide a link to a live example, or an unambiguous set of steps to -->
<!-- reproduce this bug. Include code to reproduce, if relevant. -->

## Your Environment
<!-- Include as many relevant details about the environment you experienced the bug in -->

* Library version:
* Java (and/or Kotlin) version:
* Link to your project (if it's a public repository):
6 changes: 3 additions & 3 deletions .github/ISSUE_TEMPLATE/feature-request.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ name: Feature request
about: Suggest new features/changes
labels: feature
---
<!-- Your feature request may already be reported! -->
<!-- Your feature request may already be reported. -->
<!-- Please search in the [issues](https://github.com/coditory/sherlock-distributed-lock/issues) before creating a new one. -->

## Context
<!--- What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->

## Expected Behavior
<!--- If you're suggesting a change/improvement, tell us how it should work -->
<!--- If you're suggesting a change/improvement, describe how it should work. -->
<!--- Propose a solution -->

## Current Behavior
<!--- If suggesting a change/improvement, explain the difference from the current behavior if it exists -->
<!--- If suggesting a change/improvement, explain the difference from the current behavior if it exists. -->
11 changes: 4 additions & 7 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@

## Changes

<!-- Shortly describe what you want to accomplish with this PR -->
<!-- Add a link to the issue if available -->
<!-- Shortly describe what you want to accomplish with this PR. -->
<!-- Add a link to the issue if available. -->

## Checklist

- [ ] I have tested that there is no similar [pull request](https://github.com/coditory/klog/pulls) already submitted
- [ ] I have read [contributing.md](https://github.com/coditory/klog/blob/master/.github/CONTRIBUTING.md) and applied to
the rules
- [ ] I have read [contributing.md](https://github.com/coditory/klog/blob/master/.github/CONTRIBUTING.md) and applied to the rules
- [ ] I have unit tested code changes and performed a self-review
- [ ] I
have [tested plugin change locally](https://github.com/coditory/klog/blob/master/.github/CONTRIBUTING.md#validate-changes-locally)
on a sample project
- [ ] I have [tested plugin change locally](https://github.com/coditory/klog/blob/master/.github/CONTRIBUTING.md#validate-changes-locally) on a sample project
14 changes: 14 additions & 0 deletions .github/workflows/labeler.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name: Labeler

on: [pull_request_target]

jobs:
labeler:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/labeler@v4
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ object SampleRunner {
@JvmStatic
fun main(args: Array<String>) {
val l = Klog.logger<SampleRunner>()
val e = IllegalArgumentException("Sample exception")
l.error(e) { "Testing error" }
// runBlocking {
// repeat(10000) {
// launch {
Expand Down
13 changes: 13 additions & 0 deletions klog/src/main/kotlin/com/coditory/klog/Klog.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
package com.coditory.klog

import com.coditory.klog.config.KlogConfig
import com.coditory.klog.config.KlogConfigBuilder
import com.coditory.klog.config.klogConfig
import com.coditory.klog.publish.SystemOutPublisher
import kotlinx.coroutines.runBlocking
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass

fun klog(init: KlogConfigBuilder.() -> Unit): Klog {
val config = KlogConfigBuilder()
config.init()
return Klog(config.build())
}

class Klog(config: KlogConfig) {
private val loggers = ConcurrentHashMap<String, KlogLoggerHolder>()
private var context: KlogContext = KlogContext.build(config)
Expand Down Expand Up @@ -71,6 +78,12 @@ class Klog(config: KlogConfig) {
GLOBAL_INSTANCE.reconfigure(config)
}

fun configure(init: KlogConfigBuilder.() -> Unit) {
val config = KlogConfigBuilder()
config.init()
GLOBAL_INSTANCE.reconfigure(config.build())
}

fun flush() {
GLOBAL_INSTANCE.flush()
}
Expand Down
3 changes: 2 additions & 1 deletion klog/src/main/kotlin/com/coditory/klog/LogEventField.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ enum class LogEventField {
LOGGER,
MESSAGE,
ITEMS,
EXCEPTION,
;

internal fun skip(
Expand All @@ -27,7 +28,7 @@ enum class LogEventField {

companion object {
fun all(): List<LogEventField> {
return listOf(TIMESTAMP, LEVEL, THREAD, CONTEXT, LOGGER, MESSAGE, ITEMS)
return listOf(TIMESTAMP, LEVEL, THREAD, CONTEXT, LOGGER, MESSAGE, ITEMS, EXCEPTION)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ class InMemoryPublisher : BlockingPublisher {
fun getLogs(): List<LogEvent> = events

fun getLastLog(): LogEvent? = events.lastOrNull()

fun clear() {
events.clear()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class SystemOutPublisher(
}

fun json(): SystemOutPublisher {
val formatter = JsonLogEventSerializer.default()
val formatter = JsonLogEventSerializer()
return SystemOutPublisher(formatter)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
package com.coditory.klog.text.json

import com.coditory.klog.text.shared.SizedAppendable.Companion.MAX_LENGTH_MARKER
import kotlin.math.min

internal class JsonEscapedAppendable(
private val appendable: Appendable,
private val maxLength: Int = Int.MAX_VALUE,
private val maxLengthMarker: String = MAX_LENGTH_MARKER,
) : Appendable {
private var length = 0

override fun append(csq: CharSequence?): Appendable {
if (length >= maxLength) return this
if (csq != null) {
JsonEncoder.encode(csq, appendable)
val csqLength = min(csq.length, maxLength - length)
length += csqLength
JsonEncoder.encode(csq, appendable, start = 0, end = csqLength)
appendMaxLengthMarker()
}
return this
}
Expand All @@ -15,14 +26,27 @@ internal class JsonEscapedAppendable(
start: Int,
end: Int,
): Appendable {
if (csq != null) {
JsonEncoder.encode(csq, appendable, start = start, end = end)
if (length >= maxLength) return this
if (csq != null && start < end) {
val csqLength = min(end - start, maxLength - length)
length += csqLength
JsonEncoder.encode(csq, appendable, start = start, end = start + csqLength)
appendMaxLengthMarker()
}
return this
}

override fun append(ch: Char): Appendable {
if (length >= maxLength) return this
length++
JsonEncoder.encode(ch, appendable)
appendMaxLengthMarker()
return this
}

private fun appendMaxLengthMarker() {
if (length >= maxLength) {
JsonEncoder.encode(maxLengthMarker, appendable)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.coditory.klog.text.json

import com.coditory.klog.text.plain.PlainTextExceptionFormatter

fun interface JsonExceptionFormatter {
fun format(
throwable: Throwable,
appendable: Appendable,
)

companion object {
fun from(
formatter: PlainTextExceptionFormatter,
escape: Boolean = true,
): JsonExceptionFormatter {
return JsonExceptionFormatter { throwable, appendable ->
appendable.append('"')
val wrapped = if (escape) JsonEscapedAppendable(appendable) else appendable
formatter.format(throwable, wrapped)
appendable.append('"')
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.coditory.klog.text.json
import com.coditory.klog.LogEvent
import com.coditory.klog.LogEventField
import com.coditory.klog.text.TextLogEventSerializer
import com.coditory.klog.text.plain.PlainTextMessageFormatter
import com.coditory.klog.text.shared.SizedAppendable

class JsonLogEventSerializer(
Expand All @@ -16,13 +17,15 @@ class JsonLogEventSerializer(
private val levelFormatter: JsonLevelFormatter = JsonLevelFormatter.default(),
private val loggerNameFormatter: JsonStringFormatter = JsonStringFormatter.default(escape = false),
private val threadFormatter: JsonStringFormatter = JsonStringFormatter.default(escape = false),
private val messageFormatter: JsonStringFormatter = JsonStringFormatter.default(maxLength = 10 * 1024),
private val messageFormatter: JsonMessageFormatter = JsonMessageFormatter.from(PlainTextMessageFormatter.messageAndException()),
private val contextFormatter: JsonContextFormatter = JsonContextFormatter.default(),
private val itemsFormatter: JsonMapFormatter = JsonMapFormatter.default(),
private val exceptionFormatter: JsonExceptionFormatter? = null,
) : TextLogEventSerializer {
private val fieldPaths =
LogEventField.all()
.filter { whitelist.contains(it) }
.filter { it != LogEventField.EXCEPTION || exceptionFormatter != null }
.associateWith { field ->
val name = fieldNames[field] ?: fieldNameMapper?.invoke(field) ?: field.name.lowercase()
val path =
Expand Down Expand Up @@ -112,6 +115,7 @@ class JsonLogEventSerializer(
LogEventField.CONTEXT -> formatContext(event, appendable)
LogEventField.MESSAGE -> formatMessage(event, appendable)
LogEventField.ITEMS -> formatItems(event, appendable)
LogEventField.EXCEPTION -> formatException(event, appendable)
}
}

Expand Down Expand Up @@ -154,7 +158,7 @@ class JsonLogEventSerializer(
event: LogEvent,
appendable: Appendable,
) {
messageFormatter.format(event.message, appendable)
messageFormatter.format(event.message, event.throwable, appendable)
}

private fun formatItems(
Expand All @@ -165,6 +169,15 @@ class JsonLogEventSerializer(
itemsFormatter.format(items, appendable)
}

private fun formatException(
event: LogEvent,
appendable: Appendable,
) {
if (exceptionFormatter != null && event.throwable != null) {
exceptionFormatter.format(event.throwable, appendable)
}
}

private data class Node(
val name: String,
val value: LogEventField? = null,
Expand Down Expand Up @@ -199,10 +212,4 @@ class JsonLogEventSerializer(
addChild(child, idx + 1, path, value)
}
}

companion object {
fun default(): JsonLogEventSerializer {
return JsonLogEventSerializer()
}
}
}
Loading

0 comments on commit 1f2993f

Please sign in to comment.