REPOSITORY / ScuroNeko/SNekLog
Compare commits
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6d15b530f
|
||
|
|
b7fa3f7606
|
||
|
|
812caed471
|
||
|
|
3eac1851ec
|
||
|
|
b4c9203a79
|
||
|
|
19f8750d35
|
||
|
|
d534f92d48
|
||
|
|
14b787710c
|
||
|
|
9268e222ab
|
||
|
|
6456d4d95d | ||
|
|
5d96c6fbae
|
||
|
|
badee2c598
|
||
|
|
6112a707c7
|
||
|
|
956755fe82 | ||
|
|
44ab702369 |
@@ -0,0 +1,12 @@
|
||||
name: Golang lint
|
||||
run-name: Linting code
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: go-latest
|
||||
steps:
|
||||
- name: Checkout repository code
|
||||
uses: actions/checkout@v6
|
||||
- name: Run golangci-lint
|
||||
run: golangci-lint run
|
||||
@@ -1,3 +1,5 @@
|
||||
.idea/
|
||||
.vscode/
|
||||
.codex
|
||||
test/
|
||||
*.log
|
||||
@@ -0,0 +1,675 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
@@ -1,2 +1,224 @@
|
||||
# ScuroLogger (slog)
|
||||
# SNekLog (ScuroNeko Logger)
|
||||
|
||||
Small structured logger for Go with text and JSON output, multiple writers, and optional traceback metadata.
|
||||
|
||||
Russian version: [README_ru.md](README_ru.md)
|
||||
|
||||
## Features
|
||||
|
||||
- Fan out the same record to multiple destinations.
|
||||
- Text and JSON writers.
|
||||
- `stdout`, files, and arbitrary external `io.Writer` values.
|
||||
- Optional timestamps for text output.
|
||||
- Compact traceback metadata for text writers and full traceback slices for JSON.
|
||||
- Message replacement for masking secrets or normalizing output.
|
||||
- Explicit ownership rules for writer closing.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
go get git.scuroneko.dev/scuroneko/sneklog/v2
|
||||
```
|
||||
|
||||
## Quick start
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"git.scuroneko.dev/scuroneko/sneklog/v2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := sneklog.NewLogger().
|
||||
SetName("API").
|
||||
SetLevel(sneklog.DEBUG).
|
||||
AddReplacer("SOME_SECRET", "<redacted>")
|
||||
|
||||
text := logger.CreateTextStdoutWriter()
|
||||
jsonFile, err := logger.CreateJsonFileWriter("logs/app.json")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
logger.AddWriters(text, jsonFile)
|
||||
|
||||
logger.Infoln("service started")
|
||||
logger.Warnln("cache miss")
|
||||
logger.Errorln("request failed")
|
||||
logger.Debugln("debug details")
|
||||
logger.Infoln("token", "SOME_SECRET")
|
||||
|
||||
if err := logger.Close(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Defaults
|
||||
|
||||
`NewLogger()` starts with:
|
||||
|
||||
- `Prefix("LOG")`
|
||||
- `Level(sneklog.FATAL)`
|
||||
- `JsonPretty(false)`
|
||||
- text formatter: `sneklog.DefaultTextFormatter`
|
||||
- JSON formatter: `sneklog.DefaultJsonFormatter`
|
||||
|
||||
`CreateLogger()` is still available for backward compatibility.
|
||||
|
||||
Important: with the current level ordering, `Level(sneklog.FATAL)` allows `INFO`, `WARN`, `ERROR`, and `FATAL`, but not `DEBUG`. Use `Level(sneklog.DEBUG)` to enable every level.
|
||||
|
||||
If you want classic threshold filtering instead, call `SetThresholdMode(true)` and
|
||||
configure levels with `NewThresholdLogLevel(...)` or
|
||||
`NewThresholdLogLevelWithColors(...)`.
|
||||
|
||||
## Writers and ownership
|
||||
|
||||
`Logger.Close()` only closes writers created by the logger itself:
|
||||
|
||||
- `CreateTextFileWriter(...)`
|
||||
- `CreateJsonFileWriter(...)`
|
||||
|
||||
The following writers remain owned by the caller and are not closed by `Logger.Close()`:
|
||||
|
||||
- `CreateTextWriter(existingWriter)`
|
||||
- `CreateJsonWriter(existingWriter)`
|
||||
- `CreateTextStdoutWriter()`
|
||||
- `CreateJsonStdoutWriter()`
|
||||
|
||||
This makes it safe to plug in `bytes.Buffer`, network writers, and other externally managed resources.
|
||||
|
||||
## Output formats
|
||||
|
||||
Text writers render records like:
|
||||
|
||||
```text
|
||||
2026-03-17T14:05:09+03:00 info API: service started
|
||||
```
|
||||
|
||||
Use `SetFormatter` on a writer to customize timestamps, traceback fields, colors, and message layout.
|
||||
|
||||
JSON writers emit objects with this shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"time": "2026-03-17T14:05:09.123456789+03:00",
|
||||
"level": "info",
|
||||
"prefix": "API",
|
||||
"message": "service started",
|
||||
"traceback": [
|
||||
{
|
||||
"method": "main",
|
||||
"filename": "main.go",
|
||||
"line": 27,
|
||||
"signature": "main.main",
|
||||
"fullPath": "/path/to/main.go"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
When `JsonPretty(true)` is enabled, JSON is indented.
|
||||
|
||||
## Custom levels and colors
|
||||
|
||||
You can define your own levels and assign ANSI, 256-color, or RGB colors, plus text attributes such as `Bold` or `Italic`.
|
||||
|
||||
```go
|
||||
httpDelete := sneklog.NewLogLevel(0, "delete")
|
||||
httpDelete.SetBackgroundRGB(128, 0, 0)
|
||||
httpDelete.AddAttribute(sneklog.Italic).AddAttribute(sneklog.Bold)
|
||||
|
||||
httpCache := sneklog.NewLogLevel(0, "cache")
|
||||
httpCache.SetForeground256Color(214)
|
||||
```
|
||||
|
||||
Because `LogLevel` setters mutate the level in place, call them on a variable, not on a temporary value returned by `NewLogLevel(...)`.
|
||||
Short forms such as `SetFgColor` and `SetBgColor` remain available for backward compatibility.
|
||||
|
||||
Common severities also have dedicated helpers:
|
||||
|
||||
```go
|
||||
access := sneklog.NewInfoLogLevelWithColors("access", sneklog.FgCyan, sneklog.BgNone)
|
||||
audit := sneklog.NewWarnLogLevel("audit")
|
||||
```
|
||||
|
||||
These helpers keep the legacy severity index for backward compatibility and also
|
||||
assign default threshold values:
|
||||
|
||||
- `INFO`: `th=10`
|
||||
- `WARN`: `th=20`
|
||||
- `ERROR`: `th=30`
|
||||
- `FATAL`: `th=40`
|
||||
- `DEBUG`: `th=0`
|
||||
|
||||
To define custom threshold-based levels explicitly:
|
||||
|
||||
```go
|
||||
trace := sneklog.NewThresholdLogLevelWithColors(4, 5, "trace", sneklog.FgHiBlack, sneklog.BgNone)
|
||||
audit := sneklog.NewThresholdLogLevel(1, 25, "audit")
|
||||
|
||||
logger := sneklog.NewLogger().
|
||||
SetLevel(audit).
|
||||
SetThresholdMode(true)
|
||||
|
||||
logger.Print(trace, "verbose trace") // filtered out
|
||||
logger.Print(audit, "audit event") // allowed
|
||||
```
|
||||
|
||||
HTTP method-specific predefined levels are available out of the box:
|
||||
|
||||
```go
|
||||
level := sneklog.LogLevelForMethod(http.MethodPost)
|
||||
logger.Print(level, "POST /users")
|
||||
```
|
||||
|
||||
When comparing levels:
|
||||
|
||||
- use `SameLevel` if only the legacy severity index matters;
|
||||
- use `SameThreshold` if only threshold filtering matters;
|
||||
- use `Equal` if the full configuration, including threshold, colors, and attributes, must match.
|
||||
|
||||
## Message replacement
|
||||
|
||||
`AddReplacer(old, new)` replaces matching text in every message before the
|
||||
record reaches any writer. Replacement rules are applied in the order they are
|
||||
added.
|
||||
|
||||
```go
|
||||
logger := sneklog.CreateLogger().
|
||||
Level(sneklog.DEBUG).
|
||||
AddReplacer("SOME_SECRET", "<redacted>").
|
||||
AddReplacer("user@example.com", "<email>")
|
||||
|
||||
logger.Infoln("login token:", "SOME_SECRET")
|
||||
```
|
||||
|
||||
This writes `<redacted>` instead of `SOME_SECRET` in both text and JSON output.
|
||||
An empty `old` value is ignored.
|
||||
|
||||
## API summary
|
||||
|
||||
- `Info`, `Warn`, `Error`, `Debug`, and `Fatal` accept a list of values.
|
||||
- `Infof`, `Warnf`, `Errorf`, `Debugf`, and `Fatalf` use `fmt.Sprintf`.
|
||||
- `Printf(level, format, args...)` formats a message for an explicit `LogLevel`.
|
||||
- The `*ln` methods preserve newline semantics, which is useful for `stdout`, Docker, and line-based collectors.
|
||||
- `Fatal`, `Fatalf`, and `Fatalln` call `os.Exit(1)` after writing the message.
|
||||
- `AddReplacer` masks or rewrites message text before records are sent to writers.
|
||||
|
||||
## Traceback behavior
|
||||
|
||||
- Text writers use the nearest user stack frame.
|
||||
- JSON writers receive the full traceback slice.
|
||||
- Internal `sneklog` frames and `runtime` frames are filtered out.
|
||||
|
||||
## Repository example
|
||||
|
||||
See [examples/main.go](examples/main.go).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under GNU GPLv3. See [LICENSE](LICENSE).
|
||||
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
# SNekLog (ScuroNeko Logger)
|
||||
|
||||
Небольшой структурированный логгер для Go с текстовым и JSON-выводом, несколькими writer'ами и настраиваемыми traceback-метаданными.
|
||||
|
||||
English version: [README.md](README.md)
|
||||
|
||||
## Возможности
|
||||
|
||||
- Одновременная запись в несколько destinations.
|
||||
- Текстовый и JSON-форматы.
|
||||
- `stdout`, файлы и любые внешние `io.Writer`.
|
||||
- Опциональные timestamp'ы для текстового вывода.
|
||||
- Компактный traceback для текстовых writer'ов и полный traceback для JSON.
|
||||
- Замена текста в сообщениях для маскирования секретов или нормализации вывода.
|
||||
- Явные правила владения writer'ами при `Close()`.
|
||||
|
||||
## Установка
|
||||
|
||||
```bash
|
||||
go get git.scuroneko.dev/scuroneko/sneklog/v2
|
||||
```
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"git.scuroneko.dev/scuroneko/sneklog/v2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := sneklog.NewLogger().
|
||||
SetName("API").
|
||||
SetLevel(sneklog.DEBUG).
|
||||
AddReplacer("SOME_SECRET", "<redacted>")
|
||||
|
||||
text := logger.CreateTextStdoutWriter()
|
||||
jsonFile, err := logger.CreateJsonFileWriter("logs/app.json")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
logger.AddWriters(text, jsonFile)
|
||||
|
||||
logger.Infoln("service started")
|
||||
logger.Warnln("cache miss")
|
||||
logger.Errorln("request failed")
|
||||
logger.Debugln("debug details")
|
||||
logger.Infoln("token", "SOME_SECRET")
|
||||
|
||||
if err := logger.Close(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Значения по умолчанию
|
||||
|
||||
`NewLogger()` создает логгер со следующими настройками:
|
||||
|
||||
- `Prefix("LOG")`
|
||||
- `Level(sneklog.FATAL)`
|
||||
- `JsonPretty(false)`
|
||||
- текстовый formatter: `sneklog.DefaultTextFormatter`
|
||||
- JSON formatter: `sneklog.DefaultJsonFormatter`
|
||||
|
||||
`CreateLogger()` по-прежнему доступен для обратной совместимости.
|
||||
|
||||
Важно: в текущей модели уровней `Level(sneklog.FATAL)` пропускает `INFO`, `WARN`, `ERROR` и `FATAL`, но не `DEBUG`. Чтобы включить все сообщения, используйте `Level(sneklog.DEBUG)`.
|
||||
|
||||
Если нужна классическая threshold-фильтрация, включите `SetThresholdMode(true)` и
|
||||
задавайте уровни через `NewThresholdLogLevel(...)` или
|
||||
`NewThresholdLogLevelWithColors(...)`.
|
||||
|
||||
## Writer'ы и владение
|
||||
|
||||
`Logger.Close()` закрывает только writer'ы, которые логгер создал сам:
|
||||
|
||||
- `CreateTextFileWriter(...)`
|
||||
- `CreateJsonFileWriter(...)`
|
||||
|
||||
Внешние writer'ы не закрываются:
|
||||
|
||||
- `CreateTextWriter(existingWriter)`
|
||||
- `CreateJsonWriter(existingWriter)`
|
||||
- `CreateTextStdoutWriter()`
|
||||
- `CreateJsonStdoutWriter()`
|
||||
|
||||
Это позволяет безопасно подключать `bytes.Buffer`, сетевые writer'ы и другие уже управляемые ресурсы.
|
||||
|
||||
## Форматы вывода
|
||||
|
||||
Текстовый writer формирует записи вида:
|
||||
|
||||
```text
|
||||
2026-03-17T14:05:09+03:00 info API: service started
|
||||
```
|
||||
|
||||
Используйте `SetFormatter` у writer'а, чтобы настроить timestamp'ы, traceback-поля, цвета и шаблон сообщения.
|
||||
|
||||
JSON writer записывает объект со следующими полями:
|
||||
|
||||
```json
|
||||
{
|
||||
"time": "2026-03-17T14:05:09.123456789+03:00",
|
||||
"level": "info",
|
||||
"prefix": "API",
|
||||
"message": "service started",
|
||||
"traceback": [
|
||||
{
|
||||
"method": "main",
|
||||
"filename": "main.go",
|
||||
"line": 27,
|
||||
"signature": "main.main",
|
||||
"fullPath": "/path/to/main.go"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Если включен `JsonPretty(true)`, JSON выводится с отступами.
|
||||
|
||||
## Кастомные уровни и цвета
|
||||
|
||||
Можно создавать собственные уровни и назначать им ANSI, 256-color или RGB-цвета, а также текстовые атрибуты вроде `Bold` и `Italic`.
|
||||
|
||||
```go
|
||||
httpDelete := sneklog.NewLogLevel(0, "delete")
|
||||
httpDelete.SetBackgroundRGB(128, 0, 0)
|
||||
httpDelete.AddAttribute(sneklog.Italic).AddAttribute(sneklog.Bold)
|
||||
|
||||
httpCache := sneklog.NewLogLevel(0, "cache")
|
||||
httpCache.SetForeground256Color(214)
|
||||
```
|
||||
|
||||
Так как setter'ы `LogLevel` изменяют уровень на месте, их нужно вызывать на переменной, а не на временном результате `NewLogLevel(...)`.
|
||||
Короткие формы вроде `SetFgColor` и `SetBgColor` сохранены для обратной совместимости.
|
||||
|
||||
Для стандартных severity также есть отдельные helper'ы:
|
||||
|
||||
```go
|
||||
access := sneklog.NewInfoLogLevelWithColors("access", sneklog.FgCyan, sneklog.BgNone)
|
||||
audit := sneklog.NewWarnLogLevel("audit")
|
||||
```
|
||||
|
||||
Эти helper'ы сохраняют legacy severity index для обратной совместимости и
|
||||
одновременно выставляют значения threshold по умолчанию:
|
||||
|
||||
- `INFO`: `th=10`
|
||||
- `WARN`: `th=20`
|
||||
- `ERROR`: `th=30`
|
||||
- `FATAL`: `th=40`
|
||||
- `DEBUG`: `th=0`
|
||||
|
||||
Чтобы явно создавать уровни для threshold-режима:
|
||||
|
||||
```go
|
||||
trace := sneklog.NewThresholdLogLevelWithColors(4, 5, "trace", sneklog.FgHiBlack, sneklog.BgNone)
|
||||
audit := sneklog.NewThresholdLogLevel(1, 25, "audit")
|
||||
|
||||
logger := sneklog.NewLogger().
|
||||
SetLevel(audit).
|
||||
SetThresholdMode(true)
|
||||
|
||||
logger.Print(trace, "verbose trace") // будет отфильтровано
|
||||
logger.Print(audit, "audit event") // будет записано
|
||||
```
|
||||
|
||||
Для HTTP-методов доступны готовые уровни:
|
||||
|
||||
```go
|
||||
level := sneklog.LogLevelForMethod(http.MethodPost)
|
||||
logger.Print(level, "POST /users")
|
||||
```
|
||||
|
||||
При сравнении уровней:
|
||||
|
||||
- используйте `SameLevel`, если важен только legacy severity index;
|
||||
- используйте `SameThreshold`, если важна только threshold-фильтрация;
|
||||
- используйте `Equal`, если нужно полное совпадение конфигурации, включая threshold, цвета и атрибуты.
|
||||
|
||||
## Замена сообщений
|
||||
|
||||
`AddReplacer(old, new)` заменяет найденный текст в каждом сообщении до того,
|
||||
как запись попадет в writer'ы. Правила замены применяются в порядке добавления.
|
||||
|
||||
```go
|
||||
logger := sneklog.CreateLogger().
|
||||
Level(sneklog.DEBUG).
|
||||
AddReplacer("SOME_SECRET", "<redacted>").
|
||||
AddReplacer("user@example.com", "<email>")
|
||||
|
||||
logger.Infoln("login token:", "SOME_SECRET")
|
||||
```
|
||||
|
||||
В текстовом и JSON-выводе вместо `SOME_SECRET` будет записано `<redacted>`.
|
||||
Пустое значение `old` игнорируется.
|
||||
|
||||
## API кратко
|
||||
|
||||
- `Info`, `Warn`, `Error`, `Debug`, `Fatal` принимают список значений.
|
||||
- `Infof`, `Warnf`, `Errorf`, `Debugf`, `Fatalf` используют `fmt.Sprintf`.
|
||||
- `Printf(level, format, args...)` форматирует сообщение для явного `LogLevel`.
|
||||
- Методы `*ln` добавляют семантику перевода строки, что удобно для `stdout`, Docker и line-based collectors.
|
||||
- `Fatal`, `Fatalf` и `Fatalln` вызывают `os.Exit(1)` после записи сообщения.
|
||||
- `AddReplacer` маскирует или переписывает текст сообщений перед отправкой в writer'ы.
|
||||
|
||||
## Поведение traceback
|
||||
|
||||
- Текстовые writer'ы используют ближайший пользовательский stack frame.
|
||||
- JSON writer'ы получают полный traceback.
|
||||
- Внутренние frame'ы `sneklog` и `runtime` фильтруются из traceback.
|
||||
|
||||
## Пример из репозитория
|
||||
|
||||
См. [examples/main.go](examples/main.go).
|
||||
|
||||
## Лицензия
|
||||
|
||||
Проект распространяется под GNU GPLv3. См. [LICENSE](LICENSE).
|
||||
@@ -0,0 +1,209 @@
|
||||
# Unreleased (planned v2.2.0)
|
||||
|
||||
This release expands the public LogLevel API, adds optional threshold-based
|
||||
filtering alongside the legacy severity ordering, and improves documentation
|
||||
and test coverage.
|
||||
|
||||
### Added
|
||||
|
||||
- Added dedicated log level constructors:
|
||||
- `NewInfoLogLevel`
|
||||
- `NewInfoLogLevelWithColors`
|
||||
- `NewWarnLogLevel`
|
||||
- `NewWarnLogLevelWithColors`
|
||||
- `NewErrorLogLevel`
|
||||
- `NewErrorLogLevelWithColors`
|
||||
- `NewFatalLogLevel`
|
||||
- `NewFatalLogLevelWithColors`
|
||||
- `NewDebugLogLevel`
|
||||
- `NewDebugLogLevelWithColors`
|
||||
- Added threshold-aware log level constructors:
|
||||
- `NewThresholdLogLevel`
|
||||
- `NewThresholdLogLevelWithColors`
|
||||
- Added HTTP method-specific predefined log levels:
|
||||
- `HTTPGetLevel`
|
||||
- `HTTPHeadLevel`
|
||||
- `HTTPPostLevel`
|
||||
- `HTTPPutLevel`
|
||||
- `HTTPPatchLevel`
|
||||
- `HTTPDeleteLevel`
|
||||
- `HTTPOptionsLevel`
|
||||
- `HTTPConnectLevel`
|
||||
- `HTTPTraceLevel`
|
||||
- `HTTPUnknownLevel`
|
||||
- Added `LogLevelForMethod(method string) LogLevel` to map HTTP methods to predefined log levels.
|
||||
- Added `Logger.Printf(level, format, args...)` for formatted logging with an explicit log level.
|
||||
- Added `Logger.SetThresholdMode(bool)` to switch filtering from legacy severity-index ordering to threshold-based ordering.
|
||||
- Added `LogLevel.SameLevel`, `LogLevel.SameThreshold`, and `LogLevel.Equal` for severity-only, threshold-only, and full level comparisons.
|
||||
|
||||
### Changed
|
||||
|
||||
- Refactored log level definitions into a dedicated `levels.go` file.
|
||||
- Unified `Logger.Print` and `Logger.Println` through a shared internal implementation without changing their behavior.
|
||||
- Common helper constructors such as `NewInfoLogLevel` now also assign threshold values while preserving legacy severity indexes.
|
||||
- `LogLevel.Equal` now includes threshold configuration in full equality checks.
|
||||
- Expanded test coverage for `Logger.Printf`, HTTP level mapping, constructor behavior, threshold filtering, and backward compatibility.
|
||||
|
||||
### Documentation
|
||||
|
||||
- Improved GoDoc coverage for exported types, constructors, formatters, colors, HTTP helpers, and time layouts.
|
||||
- Documented threshold mode, threshold-aware constructors, level comparison helpers, and explicit-level formatted logging.
|
||||
- Expanded inline documentation for formatter tokens and default formatter behavior.
|
||||
- Updated English and Russian README files with threshold-mode examples and comparison guidance.
|
||||
|
||||
### Compatibility
|
||||
|
||||
- No breaking API changes.
|
||||
- Existing `Print`, `Println`, predefined levels, `Level/SetLevel`, and color APIs remain compatible.
|
||||
- Legacy severity ordering remains the default; threshold filtering is enabled only when `SetThresholdMode(true)` is called.
|
||||
- `SameLevel` remains severity-only for backward compatibility, even when levels carry threshold metadata.
|
||||
|
||||
# v2.1.0
|
||||
|
||||
This release expands sneklog color customization while preserving compatibility with the v2.0.1 API.
|
||||
|
||||
## Added
|
||||
- custom LogLevel constructors with configurable colors
|
||||
- 256-color and RGB support for LogLevel
|
||||
- ANSI text attributes on LogLevel such as Bold and Italic
|
||||
- typed color helpers for foreground/background RGB and 256-color values
|
||||
- NewLogger, SetName, SetLevel, and SetJSONPretty as clearer preferred APIs
|
||||
|
||||
## Improved
|
||||
- text and JSON writer handling of trailing newline semantics
|
||||
- formatter colorization logic for foreground, background, and attributes
|
||||
- GoDoc coverage across the public API
|
||||
- English and Russian README examples and API guidance
|
||||
|
||||
## Compatibility
|
||||
- legacy APIs from v2.0.1 remain available as deprecated wrappers
|
||||
- legacy ColorStringBuilder method signatures were preserved for backward compatibility
|
||||
- deprecated methods now explicitly document their replacements and planned removal in v3
|
||||
|
||||
## Fixed
|
||||
- extra separator/space issues in Println-style output
|
||||
- attribute slice handling and defensive copying for LogLevel
|
||||
- color mode precedence when switching between ANSI, 256-color, and RGB modes
|
||||
|
||||
# v2.0.0
|
||||
|
||||
## Highlights
|
||||
|
||||
- Renamed the public Go package from `slog` to `sneklog` to avoid confusion with the standard library `log/slog` package.
|
||||
- Moved the module path to `git.scuroneko.dev/scuroneko/sneklog/v2` for Go module major-version compatibility.
|
||||
- Replaced fixed text writer settings with formatter-based output customization.
|
||||
- Added built-in ANSI color support and removed the external `github.com/fatih/color` dependency tree.
|
||||
- Formatters: a new way do display your logs!
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
- Import paths must use the `/v2` module suffix:
|
||||
|
||||
```go
|
||||
import "git.scuroneko.dev/scuroneko/sneklog/v2"
|
||||
```
|
||||
|
||||
- Package references should use `sneklog` instead of `slog`.
|
||||
- Removed `Logger.PrintTime` and `Logger.PrintTraceback`; configure output through writer formatters instead.
|
||||
- Changed text writer constructors:
|
||||
- `CreateTextWriter(w, printTraceback, printTime)` is now `CreateTextWriter(w)`.
|
||||
- `CreateTextFileWriter(path, printTraceback, printTime)` is now `CreateTextFileWriter(path)`.
|
||||
- `CreateTextStdoutWriter(printTraceback, printTime)` is now `CreateTextStdoutWriter()`.
|
||||
- Removed the old text formatting helpers: `BuildString`, `FormatTime`, `FormatTraceback`, and `FormatFullTraceback`.
|
||||
- JSON `time` values are now formatted through the configured formatter and stored as strings in `LoggerJsonMessage`.
|
||||
|
||||
## Added
|
||||
|
||||
- `Formatter` for configurable message layouts, timestamp layouts, traceback layouts, separators, and color behavior.
|
||||
- `DefaultTextFormatter` and `DefaultJsonFormatter` defaults for text and JSON writers.
|
||||
- `LoggerTextWriter.SetFormatter` and `LoggerJsonWriter.SetFormatter`.
|
||||
- Strftime-like timestamp format constants such as `RFC3339`, `Kitchen`, `DateTime`, `DateOnly`, and `TimeOnly`.
|
||||
- Built-in color types and helpers:
|
||||
- `FgColor`, `BgColor`, and `Attribute`.
|
||||
- `ColorStringBuilder`.
|
||||
- Level color getters/setters on `LogLevel`.
|
||||
- Tests covering formatter defaults, empty traceback placeholders, literal `%` sequences in messages, color controls, and JSON newline semantics.
|
||||
|
||||
## Changed
|
||||
|
||||
- Text output defaults to `DefaultTextFormatter` instead of the old hard-coded string builder.
|
||||
- JSON output defaults to `DefaultJsonFormatter` and can now format the JSON `message` field through `Formatter`.
|
||||
- Newline semantics are normalized before text and JSON formatting, so trailing `\n` controls record termination without becoming part of the message.
|
||||
- Text color output is enabled by default only for stdout/stderr.
|
||||
- Example code now demonstrates custom formatters and color configuration.
|
||||
- Go dependencies were simplified by removing:
|
||||
- `github.com/fatih/color`
|
||||
- `github.com/mattn/go-colorable`
|
||||
- `github.com/mattn/go-isatty`
|
||||
- `golang.org/x/sys`
|
||||
|
||||
## Fixed
|
||||
|
||||
- `NewFormatter()` now returns a fresh copy instead of mutating `DefaultTextFormatter`.
|
||||
- `Formatter.FormatMessage` no longer panics when called with an empty traceback.
|
||||
- Placeholder-looking text inside log messages, such as `%L` or `%s`, is preserved literally.
|
||||
- `SetColorOutput(false)` disables color output.
|
||||
- `SetColorOnlyStdout(false)` allows color output for non-stdout writers.
|
||||
|
||||
## Migration
|
||||
|
||||
Before:
|
||||
|
||||
```go
|
||||
import "git.scuroneko.dev/scuroneko/slog"
|
||||
|
||||
logger := slog.CreateLogger().
|
||||
Prefix("API").
|
||||
Level(slog.DEBUG).
|
||||
PrintTraceback(true)
|
||||
|
||||
text := logger.CreateTextStdoutWriter()
|
||||
```
|
||||
|
||||
After:
|
||||
|
||||
```go
|
||||
import sneklog "git.scuroneko.dev/scuroneko/sneklog/v2"
|
||||
|
||||
logger := sneklog.CreateLogger().
|
||||
Prefix("API").
|
||||
Level(sneklog.DEBUG)
|
||||
|
||||
formatter := sneklog.NewFormatter().
|
||||
SetFormat("%t [%L] %N: %m (%B)")
|
||||
|
||||
text := logger.CreateTextStdoutWriter().
|
||||
SetFormatter(formatter)
|
||||
```
|
||||
|
||||
# v1.2.0
|
||||
|
||||
## Highlights
|
||||
|
||||
- Added message replacement with `Logger.AddReplacer(old, new)` for masking secrets or normalizing log output.
|
||||
- Preserved the existing `LoggerWriter.Print(...any)` contract, so custom writers do not need a signature update.
|
||||
- Improved JSON writer newline handling for messages that already end with `\n`.
|
||||
|
||||
## Added
|
||||
|
||||
- `Logger.AddReplacer(old, new)` appends a replacement rule that is applied before records are sent to writers.
|
||||
- README and package GoDoc now document message replacement and include usage examples.
|
||||
- Tests covering message type preservation for custom writers, JSON empty messages, and JSON trailing newline behavior.
|
||||
|
||||
## Fixed
|
||||
|
||||
- `LoggerJsonWriter.Print` no longer panics when called with no message arguments.
|
||||
- `LoggerJsonWriter.Print` now treats a trailing newline at the end of the last message as newline semantics and does not include that newline in the JSON `message` field.
|
||||
- Log messages keep their original argument types for custom writers when no replacement rules are configured.
|
||||
|
||||
## Changed
|
||||
|
||||
- Updated the example program to demonstrate `AddReplacer`.
|
||||
- Updated dependencies:
|
||||
- `github.com/fatih/color` from `v1.18.0` to `v1.19.0`
|
||||
- `github.com/mattn/go-isatty` from `v0.0.20` to `v0.0.21`
|
||||
- `golang.org/x/sys` from `v0.42.0` to `v0.43.0`
|
||||
|
||||
## Compatibility
|
||||
|
||||
No breaking API changes are intended in this release. The public `LoggerWriter` interface continues to accept `messages ...any`.
|
||||
@@ -0,0 +1,301 @@
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FgColor is a basic ANSI foreground color code.
|
||||
type FgColor uint8
|
||||
|
||||
// BgColor is a basic ANSI background color code.
|
||||
type BgColor uint8
|
||||
|
||||
// FgColor256 is an ANSI 256-color foreground value.
|
||||
type FgColor256 uint8
|
||||
|
||||
// BgColor256 is an ANSI 256-color background value.
|
||||
type BgColor256 uint8
|
||||
|
||||
// BgColorRGB is an ANSI truecolor background value encoded as RGB bytes.
|
||||
type BgColorRGB []uint8
|
||||
|
||||
// FgColorRGB is an ANSI truecolor foreground value encoded as RGB bytes.
|
||||
type FgColorRGB []uint8
|
||||
|
||||
// Attribute is an ANSI text attribute code.
|
||||
type Attribute uint8
|
||||
|
||||
// NewBgColorRGB builds an RGB background color value.
|
||||
func NewBgColorRGB(r, g, b uint8) BgColorRGB {
|
||||
return BgColorRGB{r, g, b}
|
||||
}
|
||||
|
||||
// NewFgColorRGB builds an RGB foreground color value.
|
||||
func NewFgColorRGB(r, g, b uint8) FgColorRGB {
|
||||
return FgColorRGB{r, g, b}
|
||||
}
|
||||
|
||||
// Text attribute codes.
|
||||
const (
|
||||
Reset Attribute = iota
|
||||
Bold
|
||||
Faint
|
||||
Italic
|
||||
Underline
|
||||
BlinkSlow
|
||||
BlinkRapid
|
||||
Invert
|
||||
Conceal
|
||||
CrossedOut
|
||||
)
|
||||
|
||||
// Additional text attribute codes.
|
||||
const (
|
||||
DoubleUnderline Attribute = iota + 21 // Can be disable bold on some terminals
|
||||
DisableBold
|
||||
DisableItalic
|
||||
DisableUnderline
|
||||
DisableBlink
|
||||
DisableInvert
|
||||
DisableConceal
|
||||
DisableCrossedOut
|
||||
)
|
||||
|
||||
// Basic foreground color codes.
|
||||
const (
|
||||
FgNone = 0
|
||||
FgBlack FgColor = iota + 30
|
||||
FgRed
|
||||
FgGreen
|
||||
FgYellow
|
||||
FgBlue
|
||||
FgMagenta
|
||||
FgCyan
|
||||
FgWhite
|
||||
FgDefault FgColor = 39
|
||||
)
|
||||
|
||||
// Basic background color codes.
|
||||
const (
|
||||
BgNone = 0
|
||||
BgBlack BgColor = iota + 40
|
||||
BgRed
|
||||
BgGreen
|
||||
BgYellow
|
||||
BgBlue
|
||||
BgMagenta
|
||||
BgCyan
|
||||
BgWhite
|
||||
BgDefault BgColor = 49
|
||||
)
|
||||
|
||||
// High-intensity foreground color codes.
|
||||
const (
|
||||
FgHiBlack FgColor = iota + 90
|
||||
FgHiRed
|
||||
FgHiGreen
|
||||
FgHiYellow
|
||||
FgHiBlue
|
||||
FgHiMagenta
|
||||
FgHiCyan
|
||||
FgHiWhite
|
||||
)
|
||||
|
||||
// High-intensity background color codes.
|
||||
const (
|
||||
BgHiBlack BgColor = iota + 100
|
||||
BgHiRed
|
||||
BgHiGreen
|
||||
BgHiYellow
|
||||
BgHiBlue
|
||||
BgHiMagenta
|
||||
BgHiCyan
|
||||
BgHiWhite
|
||||
)
|
||||
|
||||
// Rarely used text attribute codes that are not supported by all terminals.
|
||||
const (
|
||||
Border Attribute = iota + 51
|
||||
Outline
|
||||
Upperline
|
||||
DisableBorderOutline
|
||||
DisableUpperline
|
||||
)
|
||||
|
||||
// ColorStringBuilder incrementally builds ANSI-colored strings.
|
||||
type ColorStringBuilder struct {
|
||||
str string
|
||||
}
|
||||
|
||||
// NewColorStringBuilder creates a builder for composing ANSI-colored strings.
|
||||
func NewColorStringBuilder() *ColorStringBuilder {
|
||||
return &ColorStringBuilder{str: ""}
|
||||
}
|
||||
|
||||
// AddAttribute appends an ANSI text attribute sequence.
|
||||
func (builder *ColorStringBuilder) AddAttribute(attr Attribute) *ColorStringBuilder {
|
||||
builder.str += attr.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddFgColor appends a basic ANSI foreground color sequence.
|
||||
func (builder *ColorStringBuilder) AddFgColor(color FgColor) *ColorStringBuilder {
|
||||
if color <= 0 {
|
||||
return builder
|
||||
}
|
||||
builder.str += color.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddBgColor appends a basic ANSI background color sequence.
|
||||
func (builder *ColorStringBuilder) AddBgColor(color BgColor) *ColorStringBuilder {
|
||||
if color <= 0 {
|
||||
return builder
|
||||
}
|
||||
builder.str += color.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddForeground256Color appends a 256-color foreground sequence.
|
||||
func (builder *ColorStringBuilder) AddForeground256Color(color FgColor256) *ColorStringBuilder {
|
||||
builder.str += color.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddColor256Fg appends a 256-color foreground sequence.
|
||||
// Deprecated: use AddForeground256Color. This method will be removed in v3.
|
||||
func (builder *ColorStringBuilder) AddColor256Fg(color uint8) *ColorStringBuilder {
|
||||
return builder.AddForeground256Color(FgColor256(color))
|
||||
}
|
||||
|
||||
// AddBackground256Color appends a 256-color background sequence.
|
||||
func (builder *ColorStringBuilder) AddBackground256Color(color BgColor256) *ColorStringBuilder {
|
||||
builder.str += color.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddColor256Bg appends a 256-color background sequence.
|
||||
// Deprecated: use AddBackground256Color. This method will be removed in v3.
|
||||
func (builder *ColorStringBuilder) AddColor256Bg(color uint8) *ColorStringBuilder {
|
||||
return builder.AddBackground256Color(BgColor256(color))
|
||||
}
|
||||
|
||||
// AddForegroundRGB appends an RGB foreground sequence.
|
||||
func (builder *ColorStringBuilder) AddForegroundRGB(color FgColorRGB) *ColorStringBuilder {
|
||||
builder.str += color.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddColorRgbFg appends an RGB foreground sequence.
|
||||
// Deprecated: use AddForegroundRGB. This method will be removed in v3.
|
||||
func (builder *ColorStringBuilder) AddColorRgbFg(r, g, b uint8) *ColorStringBuilder {
|
||||
return builder.AddForegroundRGB(FgColorRGB{r, g, b})
|
||||
}
|
||||
|
||||
// AddBackgroundRGB appends an RGB background sequence.
|
||||
func (builder *ColorStringBuilder) AddBackgroundRGB(color BgColorRGB) *ColorStringBuilder {
|
||||
builder.str += color.String()
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddColorRgbBg appends an RGB background sequence.
|
||||
// Deprecated: use AddBackgroundRGB. This method will be removed in v3.
|
||||
func (builder *ColorStringBuilder) AddColorRgbBg(r, g, b uint8) *ColorStringBuilder {
|
||||
return builder.AddBackgroundRGB(BgColorRGB{r, g, b})
|
||||
}
|
||||
|
||||
// AddReset appends the ANSI reset sequence.
|
||||
func (builder *ColorStringBuilder) AddReset() *ColorStringBuilder {
|
||||
builder.str += "\x1b[0m"
|
||||
return builder
|
||||
}
|
||||
|
||||
// AddText appends plain text to the builder.
|
||||
func (builder *ColorStringBuilder) AddText(text string) *ColorStringBuilder {
|
||||
builder.str += text
|
||||
return builder
|
||||
}
|
||||
|
||||
// String returns the built string and appends a reset sequence when needed.
|
||||
func (builder *ColorStringBuilder) String() string {
|
||||
if strings.Contains(builder.str, "\x1b[") && !strings.HasSuffix(builder.str, "\x1b[0m") {
|
||||
builder.AddReset()
|
||||
}
|
||||
return builder.str
|
||||
}
|
||||
|
||||
// String returns the ANSI escape sequence for the attribute.
|
||||
func (a Attribute) String() string {
|
||||
return fmt.Sprintf("\x1b[%dm", a)
|
||||
}
|
||||
|
||||
// Uint8 returns the raw attribute value.
|
||||
func (a Attribute) Uint8() uint8 {
|
||||
return uint8(a)
|
||||
}
|
||||
|
||||
// Int returns the raw attribute value as int.
|
||||
func (a Attribute) Int() int {
|
||||
return int(a)
|
||||
}
|
||||
|
||||
// String returns the ANSI escape sequence for the foreground color.
|
||||
func (c FgColor) String() string {
|
||||
return fmt.Sprintf("\x1b[%dm", c)
|
||||
}
|
||||
|
||||
// Uint8 returns the raw foreground color value.
|
||||
func (c FgColor) Uint8() uint8 {
|
||||
return uint8(c)
|
||||
}
|
||||
|
||||
// Int returns the raw foreground color value as int.
|
||||
func (c FgColor) Int() int {
|
||||
return int(c)
|
||||
}
|
||||
|
||||
// String returns the ANSI escape sequence for the background color.
|
||||
func (c BgColor) String() string {
|
||||
return fmt.Sprintf("\x1b[%dm", c)
|
||||
}
|
||||
|
||||
// Uint8 returns the raw background color value.
|
||||
func (c BgColor) Uint8() uint8 {
|
||||
return uint8(c)
|
||||
}
|
||||
|
||||
// Int returns the raw background color value as int.
|
||||
func (c BgColor) Int() int {
|
||||
return int(c)
|
||||
}
|
||||
|
||||
// String returns the ANSI escape sequence for the 256-color foreground value.
|
||||
func (c FgColor256) String() string { return fmt.Sprintf("\u001B[38;5;%dm", c) }
|
||||
|
||||
// Uint8 returns the raw 256-color foreground value.
|
||||
func (c FgColor256) Uint8() uint8 { return uint8(c) }
|
||||
|
||||
// Int returns the raw 256-color foreground value as int.
|
||||
func (c FgColor256) Int() int { return int(c) }
|
||||
|
||||
// String returns the ANSI escape sequence for the 256-color background value.
|
||||
func (c BgColor256) String() string { return fmt.Sprintf("\u001B[48;5;%dm", c) }
|
||||
|
||||
// Uint8 returns the raw 256-color background value.
|
||||
func (c BgColor256) Uint8() uint8 { return uint8(c) }
|
||||
|
||||
// Int returns the raw 256-color background value as int.
|
||||
func (c BgColor256) Int() int { return int(c) }
|
||||
|
||||
// String returns the ANSI escape sequence for the RGB foreground value.
|
||||
func (c FgColorRGB) String() string { return fmt.Sprintf("\x1b[38;2;%d;%d;%dm", c[0], c[1], c[2]) }
|
||||
|
||||
// Uint8 returns the raw RGB foreground components.
|
||||
func (c FgColorRGB) Uint8() []uint8 { return c }
|
||||
|
||||
// String returns the ANSI escape sequence for the RGB background value.
|
||||
func (c BgColorRGB) String() string { return fmt.Sprintf("\x1b[48;2;%d;%d;%dm", c[0], c[1], c[2]) }
|
||||
|
||||
// Uint8 returns the raw RGB background components.
|
||||
func (c BgColorRGB) Uint8() []uint8 { return c }
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package sneklog provides a small structured logger that can write the same
|
||||
// record to text and JSON outputs.
|
||||
//
|
||||
// A Logger can fan out records to stdout, files, or any external io.Writer.
|
||||
// Text writers can include timestamps and a compact traceback frame. JSON
|
||||
// writers always emit a structured traceback slice.
|
||||
//
|
||||
// CreateLogger uses the following defaults:
|
||||
// - prefix: "LOG"
|
||||
// - level: FATAL, which enables info, warn, error, and fatal records
|
||||
// - pretty JSON: disabled
|
||||
// - text formatter: DefaultTextFormatter
|
||||
// - JSON formatter: DefaultJsonFormatter
|
||||
//
|
||||
// Call Level(DEBUG) to enable all records, including debug messages.
|
||||
// AddReplacer can be used to mask or normalize message text before records are
|
||||
// passed to writers. Call SetFormatter on a writer to customize timestamps,
|
||||
// traceback fields, colors, and message layout.
|
||||
//
|
||||
// The package also provides helper constructors for common severities such as
|
||||
// NewInfoLogLevel and NewErrorLogLevel, plus predefined HTTP method-specific
|
||||
// levels such as HTTPGetLevel and HTTPPostLevel. Use LogLevelForMethod to map
|
||||
// an HTTP method to one of those predefined levels.
|
||||
//
|
||||
// Basic usage:
|
||||
//
|
||||
// logger := sneklog.CreateLogger().
|
||||
// Prefix("API").
|
||||
// Level(sneklog.DEBUG).
|
||||
// AddReplacer("secret-token", "<redacted>")
|
||||
//
|
||||
// text := logger.CreateTextStdoutWriter()
|
||||
// jsonFile, err := logger.CreateJsonFileWriter("logs/app.json")
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
//
|
||||
// logger.AddWriters(text, jsonFile)
|
||||
// logger.Infoln("service started", "secret-token")
|
||||
//
|
||||
// if err := logger.Close(); err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
//
|
||||
// Writers created with CreateTextFileWriter or CreateJsonFileWriter are owned by
|
||||
// the logger and are closed by Logger.Close. Writers created from existing
|
||||
// io.Writer values through CreateTextWriter or CreateJsonWriter remain owned by
|
||||
// the caller and are not closed by the logger.
|
||||
//
|
||||
// LogLevel values can be compared with SameLevel when only the legacy severity
|
||||
// index matters, with SameThreshold when only threshold filtering matters, or
|
||||
// with Equal when the full level configuration must match.
|
||||
package sneklog
|
||||
+80
-13
@@ -1,21 +1,88 @@
|
||||
package main
|
||||
|
||||
import "git.nix13.pw/scuroneko/slog"
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"git.scuroneko.dev/scuroneko/sneklog/v2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := slog.CreateLogger().JsonPretty(false)
|
||||
defer logger.Close()
|
||||
logger.AddWriter(logger.CreateTextStdoutWriter())
|
||||
f, err := logger.CreateJsonFileWriter("main.log")
|
||||
httpGet := sneklog.NewLogLevelWithColors(0, "get", sneklog.FgGreen, sneklog.BgNone)
|
||||
httpPost := sneklog.NewLogLevelWithColors(0, "post", sneklog.FgBlue, sneklog.BgNone)
|
||||
httpDelete := sneklog.NewLogLevel(0, "delete")
|
||||
httpDelete.SetBackgroundRGB(128, 0, 0)
|
||||
httpDelete.AddAttribute(sneklog.Italic).AddAttribute(sneklog.Bold)
|
||||
|
||||
logger := sneklog.NewLogger().
|
||||
SetName("EXAMPLE").
|
||||
SetLevel(sneklog.DEBUG).
|
||||
SetJSONPretty(true).
|
||||
AddReplacer("SOME_SECRET", "<Secret>")
|
||||
|
||||
sneklog.INFO.SetBgColor(sneklog.BgBlue).SetFgColor(sneklog.FgWhite)
|
||||
|
||||
textStdout := logger.CreateTextStdoutWriter()
|
||||
jsonStdout := logger.CreateJsonStdoutWriter()
|
||||
|
||||
formatter := sneklog.NewFormatter().
|
||||
SetFormat("[%t] [%L] [%N]: %m (%s)").
|
||||
SetTimeStampFormat(sneklog.Kitchen).
|
||||
SetTraceBackFormat("%s %f:%n %p")
|
||||
|
||||
jsonFormatter := sneklog.NewFormatter().
|
||||
SetFormat("[%L] [%N] %m").
|
||||
SetColorOutput(false).
|
||||
SetTimeStampFormat(sneklog.Kitchen)
|
||||
|
||||
textStdout.SetFormatter(formatter)
|
||||
jsonStdout.SetFormatter(jsonFormatter)
|
||||
|
||||
textFile, err := logger.CreateTextFileWriter("logs/text.log")
|
||||
if err != nil {
|
||||
_ = logger.Close()
|
||||
panic(err)
|
||||
}
|
||||
logger.AddWriter(f)
|
||||
logger.Infoln("Test")
|
||||
logger.Warnln("Test")
|
||||
logger.Errorln("Test")
|
||||
logger.Debugln("Test") // No output
|
||||
logger.Level(slog.DEBUG)
|
||||
logger.Debugln("Test") // Now we have output
|
||||
logger.Fatalln("Test") // Exit code 1
|
||||
|
||||
jsonFile, err := logger.CreateJsonFileWriter("logs/json.log")
|
||||
if err != nil {
|
||||
_ = logger.Close()
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var externalBuffer bytes.Buffer
|
||||
externalText := logger.CreateTextWriter(&externalBuffer)
|
||||
externalJSON := logger.CreateJsonWriter(&externalBuffer)
|
||||
|
||||
logger.AddWriters(
|
||||
textStdout,
|
||||
jsonStdout,
|
||||
textFile,
|
||||
jsonFile,
|
||||
externalText,
|
||||
externalJSON,
|
||||
)
|
||||
|
||||
logger.Infoln("service started")
|
||||
logger.Warnln("cache miss")
|
||||
logger.Errorln("request failed")
|
||||
logger.Debugln("debug details")
|
||||
logger.Infoln("sensitive info, SOME_SECRET")
|
||||
logger.Println(httpGet, "this can be logging of http get request/response...")
|
||||
logger.Println(httpPost, "...and this can be logging of http post request/response...")
|
||||
logger.Println(httpDelete, "...but this logging of http delete request/response with highly customizable level!")
|
||||
|
||||
if err := logger.Close(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
s := sneklog.NewColorStringBuilder().
|
||||
AddBackgroundRGB(sneklog.NewBgColorRGB(31, 41, 40)).
|
||||
AddForegroundRGB(sneklog.NewFgColorRGB(220, 215, 186)).
|
||||
AddAttribute(sneklog.Italic).AddAttribute(sneklog.Bold).
|
||||
AddText("Some Very very very cool stuff, themed in Kanagawa colors!").String()
|
||||
|
||||
println(s)
|
||||
|
||||
//fmt.Println("external buffer contents:")
|
||||
//fmt.Println(externalBuffer.String())
|
||||
}
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Formatter configures how log records are rendered.
|
||||
//
|
||||
// Format tokens:
|
||||
// - %t: time
|
||||
// - %N: name
|
||||
// - %l: level
|
||||
// - %L: uppercase level
|
||||
// - %b: first traceback frame
|
||||
// - %B: full traceback
|
||||
// - %m: message
|
||||
// - %M: method
|
||||
// - %f: filename
|
||||
// - %n: line number
|
||||
// - %s: method signature
|
||||
// - %p: full path
|
||||
//
|
||||
// Example format: "%t [%l] %N: %m (%f:%n %s)"
|
||||
//
|
||||
// TimeStampFormat uses strftime-like directives such as %Y, %m, %d, %H, %M,
|
||||
// %S, %z, and %Z.
|
||||
//
|
||||
// TraceBackFormat supports the traceback-related tokens %M, %f, %n, %s, and %p.
|
||||
type Formatter struct {
|
||||
Format string
|
||||
MessageSeparator string
|
||||
|
||||
// JSONTraceBackPath
|
||||
// If true, in traceback will be path to file, otherwise only filename.
|
||||
JSONTraceBackPath bool
|
||||
TimeStampFormat string
|
||||
TraceBackFormat string
|
||||
TraceBackSeparator string
|
||||
|
||||
ColorOutput bool
|
||||
ColorOnlyStdout bool
|
||||
}
|
||||
|
||||
// DefaultTextFormatter is the default formatter used by text writers.
|
||||
var DefaultTextFormatter = &Formatter{
|
||||
Format: "%t %l %N: %m",
|
||||
MessageSeparator: " ",
|
||||
TimeStampFormat: RFC3339,
|
||||
TraceBackFormat: "%M (%f:%n %s)",
|
||||
TraceBackSeparator: "->",
|
||||
ColorOutput: true,
|
||||
ColorOnlyStdout: true,
|
||||
}
|
||||
|
||||
// DefaultJsonFormatter is the default formatter used by JSON writers.
|
||||
var DefaultJsonFormatter = &Formatter{
|
||||
Format: "%m",
|
||||
MessageSeparator: " ",
|
||||
TimeStampFormat: RFC3339,
|
||||
ColorOutput: false,
|
||||
}
|
||||
|
||||
// NewFormatter returns a copy of the default text formatter settings.
|
||||
func NewFormatter() *Formatter {
|
||||
return &Formatter{
|
||||
Format: DefaultTextFormatter.Format,
|
||||
MessageSeparator: DefaultTextFormatter.MessageSeparator,
|
||||
TimeStampFormat: DefaultTextFormatter.TimeStampFormat,
|
||||
TraceBackFormat: DefaultTextFormatter.TraceBackFormat,
|
||||
TraceBackSeparator: DefaultTextFormatter.TraceBackSeparator,
|
||||
ColorOutput: DefaultTextFormatter.ColorOutput,
|
||||
ColorOnlyStdout: DefaultTextFormatter.ColorOnlyStdout,
|
||||
}
|
||||
}
|
||||
|
||||
// SetFormat sets the formatter template used for text rendering.
|
||||
func (f *Formatter) SetFormat(format string) *Formatter {
|
||||
f.Format = format
|
||||
return f
|
||||
}
|
||||
|
||||
// SetMessageSeparator sets the separator used to join message parts.
|
||||
func (f *Formatter) SetMessageSeparator(separator string) *Formatter {
|
||||
f.MessageSeparator = separator
|
||||
return f
|
||||
}
|
||||
|
||||
// SetTimeStampFormat sets the strftime-like format used for timestamps.
|
||||
func (f *Formatter) SetTimeStampFormat(format string) *Formatter {
|
||||
f.TimeStampFormat = format
|
||||
return f
|
||||
}
|
||||
|
||||
// SetTraceBackFormat sets the format used for a single traceback frame.
|
||||
func (f *Formatter) SetTraceBackFormat(format string) *Formatter {
|
||||
f.TraceBackFormat = format
|
||||
return f
|
||||
}
|
||||
|
||||
// SetTraceBackSeparator sets the separator used between traceback frames.
|
||||
func (f *Formatter) SetTraceBackSeparator(separator string) *Formatter {
|
||||
f.TraceBackSeparator = separator
|
||||
return f
|
||||
}
|
||||
|
||||
// SetColorOutput enables or disables colorized output.
|
||||
func (f *Formatter) SetColorOutput(color bool) *Formatter {
|
||||
f.ColorOutput = color
|
||||
return f
|
||||
}
|
||||
|
||||
// SetColorOnlyStdout restricts colorized output to stdout and stderr when enabled.
|
||||
func (f *Formatter) SetColorOnlyStdout(only bool) *Formatter {
|
||||
f.ColorOnlyStdout = only
|
||||
return f
|
||||
}
|
||||
|
||||
// FormatMessage applies the formatter template to the provided log record fields.
|
||||
func (f *Formatter) FormatMessage(level LogLevel, prefix string, tb []*MethodTraceback, messages ...any) string {
|
||||
if f == nil {
|
||||
return fmt.Sprint(messages...)
|
||||
}
|
||||
output := f.Format
|
||||
output = strings.ReplaceAll(output, "%t", f.FormatTime(time.Now()))
|
||||
output = strings.ReplaceAll(output, "%N", prefix)
|
||||
output = strings.ReplaceAll(output, "%l", level.GetName())
|
||||
output = strings.ReplaceAll(output, "%L", strings.ToUpper(level.GetName()))
|
||||
|
||||
if len(tb) > 0 {
|
||||
formattedTraceback := f.FormatTraceback(tb[0])
|
||||
output = strings.ReplaceAll(output, "%b", formattedTraceback)
|
||||
|
||||
formattedTraceback = f.FormatTracebacks(tb)
|
||||
output = strings.ReplaceAll(output, "%B", formattedTraceback)
|
||||
} else {
|
||||
output = strings.ReplaceAll(output, "%b", "")
|
||||
output = strings.ReplaceAll(output, "%B", "")
|
||||
}
|
||||
|
||||
if len(tb) > 0 {
|
||||
output = strings.ReplaceAll(output, "%M", tb[0].Method)
|
||||
output = strings.ReplaceAll(output, "%f", tb[0].Filename)
|
||||
output = strings.ReplaceAll(output, "%n", fmt.Sprintf("%d", tb[0].Line))
|
||||
output = strings.ReplaceAll(output, "%s", tb[0].Signature)
|
||||
} else {
|
||||
output = strings.ReplaceAll(output, "%M", "")
|
||||
output = strings.ReplaceAll(output, "%f", "")
|
||||
output = strings.ReplaceAll(output, "%n", "")
|
||||
output = strings.ReplaceAll(output, "%s", "")
|
||||
}
|
||||
|
||||
if f.JSONTraceBackPath && len(tb) > 0 {
|
||||
output = strings.ReplaceAll(output, "%p", tb[0].FullPath)
|
||||
} else {
|
||||
output = strings.ReplaceAll(output, "%p", "")
|
||||
}
|
||||
|
||||
message := Map(messages, func(m any) string { return fmt.Sprint(m) })
|
||||
output = strings.ReplaceAll(output, "%m", strings.Join(message, f.MessageSeparator))
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
// ColorizeString wraps a string in the ANSI color sequences defined by the level.
|
||||
func (f *Formatter) ColorizeString(s string, level LogLevel) string {
|
||||
builder := NewColorStringBuilder()
|
||||
if level.fgRgb != nil {
|
||||
builder.AddForegroundRGB(level.fgRgb)
|
||||
} else if level.fg256 > 0 {
|
||||
builder.AddForeground256Color(level.fg256)
|
||||
} else {
|
||||
builder.AddFgColor(level.fg)
|
||||
}
|
||||
|
||||
if level.bgRgb != nil {
|
||||
builder.AddBackgroundRGB(level.bgRgb)
|
||||
} else if level.bg256 > 0 {
|
||||
builder.AddBackground256Color(level.bg256)
|
||||
} else {
|
||||
builder.AddBgColor(level.bg)
|
||||
}
|
||||
|
||||
for _, attr := range level.attrs {
|
||||
builder.AddAttribute(attr)
|
||||
}
|
||||
return builder.AddText(s).AddReset().String()
|
||||
}
|
||||
|
||||
// FormatTime formats a timestamp using the formatter timestamp layout.
|
||||
func (f *Formatter) FormatTime(t time.Time) string {
|
||||
if f.TimeStampFormat == "" {
|
||||
return t.Format(time.RFC3339)
|
||||
}
|
||||
return t.Format(StrftimeToGo(f.TimeStampFormat))
|
||||
}
|
||||
|
||||
// FormatTraceback formats a single traceback frame.
|
||||
func (f *Formatter) FormatTraceback(traceback *MethodTraceback) string {
|
||||
formattedTraceback := f.TraceBackFormat
|
||||
if f.JSONTraceBackPath {
|
||||
formattedTraceback = strings.ReplaceAll(formattedTraceback, "%p", traceback.FullPath)
|
||||
} else {
|
||||
formattedTraceback = strings.ReplaceAll(formattedTraceback, "%p", "")
|
||||
}
|
||||
formattedTraceback = strings.ReplaceAll(formattedTraceback, "%M", traceback.Method)
|
||||
formattedTraceback = strings.ReplaceAll(formattedTraceback, "%f", traceback.Filename)
|
||||
formattedTraceback = strings.ReplaceAll(formattedTraceback, "%n", fmt.Sprintf("%d", traceback.Line))
|
||||
formattedTraceback = strings.ReplaceAll(formattedTraceback, "%s", traceback.Signature)
|
||||
return formattedTraceback
|
||||
}
|
||||
|
||||
// FormatTracebacks formats and joins multiple traceback frames.
|
||||
func (f *Formatter) FormatTracebacks(traceback []*MethodTraceback) string {
|
||||
var formattedTraceback []string
|
||||
for _, frame := range traceback {
|
||||
formattedTraceback = append(formattedTraceback, f.FormatTraceback(frame))
|
||||
}
|
||||
return strings.Join(formattedTraceback, f.TraceBackSeparator)
|
||||
}
|
||||
@@ -1,11 +1,3 @@
|
||||
module git.nix13.pw/scuroneko/slog
|
||||
module git.scuroneko.dev/scuroneko/sneklog/v2
|
||||
|
||||
go 1.25
|
||||
|
||||
require github.com/fatih/color v1.18.0
|
||||
|
||||
require (
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
)
|
||||
go 1.26
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package sneklog
|
||||
|
||||
import "net/http"
|
||||
|
||||
// HTTP method-specific log levels.
|
||||
var (
|
||||
HTTPGetLevel = NewInfoLogLevelWithColors("get", FgGreen, BgNone)
|
||||
HTTPHeadLevel = NewInfoLogLevelWithColors("head", FgCyan, BgNone)
|
||||
HTTPPostLevel = NewInfoLogLevelWithColors("post", FgBlue, BgNone)
|
||||
HTTPPutLevel = NewInfoLogLevelWithColors("put", FgYellow, BgNone)
|
||||
HTTPPatchLevel = NewInfoLogLevelWithColors("patch", FgMagenta, BgNone)
|
||||
HTTPDeleteLevel = NewInfoLogLevelWithColors("delete", FgRed, BgNone)
|
||||
)
|
||||
|
||||
// Additional HTTP method-specific log levels.
|
||||
var (
|
||||
HTTPOptionsLevel = NewDebugLogLevelWithColors("options", FgWhite, BgNone)
|
||||
HTTPConnectLevel = NewDebugLogLevelWithColors("connect", FgCyan, BgNone)
|
||||
HTTPTraceLevel = NewDebugLogLevelWithColors("trace", FgWhite, BgNone)
|
||||
HTTPUnknownLevel = NewDebugLogLevelWithColors("http", FgWhite, BgNone)
|
||||
)
|
||||
|
||||
// LogLevelForMethod returns the predefined log level associated with an HTTP method.
|
||||
func LogLevelForMethod(method string) LogLevel {
|
||||
switch method {
|
||||
case http.MethodGet:
|
||||
return HTTPGetLevel
|
||||
case http.MethodHead:
|
||||
return HTTPHeadLevel
|
||||
case http.MethodPost:
|
||||
return HTTPPostLevel
|
||||
case http.MethodPut:
|
||||
return HTTPPutLevel
|
||||
case http.MethodPatch:
|
||||
return HTTPPatchLevel
|
||||
case http.MethodDelete:
|
||||
return HTTPDeleteLevel
|
||||
case http.MethodOptions:
|
||||
return HTTPOptionsLevel
|
||||
case http.MethodConnect:
|
||||
return HTTPConnectLevel
|
||||
case http.MethodTrace:
|
||||
return HTTPTraceLevel
|
||||
default:
|
||||
return HTTPUnknownLevel
|
||||
}
|
||||
}
|
||||
@@ -1,91 +1,130 @@
|
||||
package slog
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Infof logs a formatted info message.
|
||||
func (l *Logger) Infof(format string, args ...any) {
|
||||
l.print(INFO, fmt.Sprintf(format, args...))
|
||||
l.Print(INFO, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// Info logs an info message.
|
||||
func (l *Logger) Info(m ...any) {
|
||||
l.print(INFO, m...)
|
||||
l.Print(INFO, m...)
|
||||
}
|
||||
|
||||
// Infoln logs an info message and appends a newline semantic for writers that need it.
|
||||
func (l *Logger) Infoln(m ...any) {
|
||||
l.println(INFO, m...)
|
||||
l.Println(INFO, m...)
|
||||
}
|
||||
|
||||
// Warnf logs a formatted warning message.
|
||||
func (l *Logger) Warnf(format string, args ...any) {
|
||||
l.print(WARN, fmt.Sprintf(format, args...))
|
||||
l.Print(WARN, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// Warn logs a warning message.
|
||||
func (l *Logger) Warn(m ...any) {
|
||||
l.print(WARN, m...)
|
||||
l.Print(WARN, m...)
|
||||
}
|
||||
|
||||
// Warnln logs a warning message with newline semantic.
|
||||
func (l *Logger) Warnln(m ...any) {
|
||||
l.println(WARN, m...)
|
||||
l.Println(WARN, m...)
|
||||
}
|
||||
|
||||
// Errorf logs a formatted error message.
|
||||
func (l *Logger) Errorf(format string, args ...any) {
|
||||
l.print(ERROR, fmt.Sprintf(format, args...))
|
||||
l.Print(ERROR, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// Error logs an error message.
|
||||
func (l *Logger) Error(m ...any) {
|
||||
l.print(ERROR, m...)
|
||||
l.Print(ERROR, m...)
|
||||
}
|
||||
|
||||
// Errorln logs an error message with newline semantic.
|
||||
func (l *Logger) Errorln(m ...any) {
|
||||
l.println(ERROR, m...)
|
||||
l.Println(ERROR, m...)
|
||||
}
|
||||
|
||||
// Fatalf logs a formatted fatal message and exits the process with code 1.
|
||||
func (l *Logger) Fatalf(format string, args ...any) {
|
||||
l.print(FATAL, fmt.Sprintf(format, args...))
|
||||
l.Print(FATAL, fmt.Sprintf(format, args...))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Fatal logs a fatal message and exits the process with code 1.
|
||||
func (l *Logger) Fatal(m ...any) {
|
||||
l.print(FATAL, m...)
|
||||
l.Print(FATAL, m...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Fatalln logs a fatal message with newline semantic and exits the process with code 1.
|
||||
func (l *Logger) Fatalln(m ...any) {
|
||||
l.println(FATAL, m...)
|
||||
l.Println(FATAL, m...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Debugf logs a formatted debug message.
|
||||
func (l *Logger) Debugf(format string, args ...any) {
|
||||
l.print(DEBUG, fmt.Sprintf(format, args...))
|
||||
l.Print(DEBUG, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// Debug logs a debug message.
|
||||
func (l *Logger) Debug(m ...any) {
|
||||
l.print(DEBUG, m...)
|
||||
l.Print(DEBUG, m...)
|
||||
}
|
||||
|
||||
// Debugln logs a debug message with newline semantic.
|
||||
func (l *Logger) Debugln(m ...any) {
|
||||
l.println(DEBUG, m...)
|
||||
l.Println(DEBUG, m...)
|
||||
}
|
||||
|
||||
// Write message without trailing "\n"
|
||||
// Good for database
|
||||
func (l *Logger) print(level LogLevel, m ...any) {
|
||||
if l.level.n < level.n {
|
||||
func (l *Logger) print(level LogLevel, newline bool, m ...any) {
|
||||
if l.threshold && l.level.th < level.th {
|
||||
return
|
||||
} else if l.level.n < level.n {
|
||||
return
|
||||
}
|
||||
if len(l.writers) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
tb := getFullTraceback(0)
|
||||
tb := getFullTraceback(1)
|
||||
messages := l.replaceAll(m...)
|
||||
if newline {
|
||||
messages = append(messages, any("\n"))
|
||||
}
|
||||
for _, writer := range l.writers {
|
||||
err := writer.Print(level, l.prefix, tb, m...)
|
||||
if writer == nil {
|
||||
continue
|
||||
}
|
||||
err := writer.Print(level, l.prefix, tb, messages...)
|
||||
if err != nil {
|
||||
l.Error(err)
|
||||
l.reportWriterError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Docker requires "\n" at end to write to log.
|
||||
// print not work for docker, otherwise it will work and write into stdout
|
||||
func (l *Logger) println(level LogLevel, m ...any) {
|
||||
if l.level.n < level.n {
|
||||
// Print logs a message without appending a trailing newline semantic.
|
||||
func (l *Logger) Print(level LogLevel, m ...any) { l.print(level, false, m...) }
|
||||
|
||||
// Println logs a message and appends a trailing newline semantic for writers that need it.
|
||||
func (l *Logger) Println(level LogLevel, m ...any) { l.print(level, true, m...) }
|
||||
|
||||
// Printf formats according to a format specifier and logs the resulting message.
|
||||
func (l *Logger) Printf(level LogLevel, format string, args ...any) {
|
||||
l.print(level, false, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// reportWriterError writes internal writer failures directly to stderr to avoid
|
||||
// re-entering the same logger path that just failed.
|
||||
func (l *Logger) reportWriterError(err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
tb := getFullTraceback(0)
|
||||
for _, writer := range l.writers {
|
||||
err := writer.Print(level, l.prefix, tb, append(m, "\n")...)
|
||||
if err != nil {
|
||||
l.Error(err)
|
||||
}
|
||||
}
|
||||
_, _ = fmt.Fprintf(os.Stderr, "[%s] logger writer error: %v\n", l.prefix, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package sneklog
|
||||
|
||||
// Predefined log levels.
|
||||
var (
|
||||
INFO = NewInfoLogLevelWithColors("info", FgWhite, BgNone)
|
||||
WARN = NewWarnLogLevelWithColors("warn", FgHiYellow, BgNone)
|
||||
ERROR = NewErrorLogLevelWithColors("error", FgHiRed, BgNone)
|
||||
FATAL = NewFatalLogLevelWithColors("fatal", FgRed, BgNone)
|
||||
DEBUG = NewDebugLogLevelWithColors("debug", FgGreen, BgNone)
|
||||
)
|
||||
|
||||
// LogLevel describes a logging severity.
|
||||
type LogLevel struct {
|
||||
n uint8
|
||||
th uint8
|
||||
t string
|
||||
|
||||
fg FgColor
|
||||
fg256 FgColor256
|
||||
fgRgb FgColorRGB
|
||||
|
||||
bg BgColor
|
||||
bg256 BgColor256
|
||||
bgRgb BgColorRGB
|
||||
|
||||
attrs []Attribute
|
||||
}
|
||||
|
||||
// NewLogLevel creates a log level without predefined colors.
|
||||
// Deprecated: use NewThresholdLogLevel. This function will be removed in v3.
|
||||
func NewLogLevel(index uint8, name string) LogLevel {
|
||||
return NewLogLevelWithColors(index, name, 0, 0)
|
||||
}
|
||||
|
||||
// NewLogLevelWithColors creates a log level with ANSI foreground and background colors.
|
||||
// Deprecated: use NewThresholdLogLevelWithColors. This function will be removed in v3.
|
||||
func NewLogLevelWithColors(index uint8, name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return LogLevel{n: index, t: name, fg: fg, bg: bg, attrs: []Attribute{}}
|
||||
}
|
||||
|
||||
// NewThresholdLogLevel creates a log level with both a legacy severity index and
|
||||
// a threshold value used when Logger.SetThresholdMode(true) is enabled.
|
||||
func NewThresholdLogLevel(index, th uint8, name string) LogLevel {
|
||||
return NewThresholdLogLevelWithColors(index, th, name, FgNone, BgNone)
|
||||
}
|
||||
|
||||
// NewThresholdLogLevelWithColors creates a log level with both a legacy
|
||||
// severity index and a threshold value, plus ANSI foreground and background
|
||||
// colors.
|
||||
func NewThresholdLogLevelWithColors(index, th uint8, name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return LogLevel{n: index, th: th, t: name, fg: fg, bg: bg, attrs: []Attribute{}}
|
||||
}
|
||||
|
||||
// NewInfoLogLevel creates an info-level log level without predefined colors.
|
||||
func NewInfoLogLevel(name string) LogLevel { return NewThresholdLogLevel(0, 10, name) }
|
||||
|
||||
// NewInfoLogLevelWithColors creates an info-level log level with ANSI colors.
|
||||
func NewInfoLogLevelWithColors(name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return NewThresholdLogLevelWithColors(0, 10, name, fg, bg)
|
||||
}
|
||||
|
||||
// NewWarnLogLevel creates a warn-level log level without predefined colors.
|
||||
func NewWarnLogLevel(name string) LogLevel { return NewThresholdLogLevel(1, 20, name) }
|
||||
|
||||
// NewWarnLogLevelWithColors creates a warn-level log level with ANSI colors.
|
||||
func NewWarnLogLevelWithColors(name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return NewThresholdLogLevelWithColors(1, 20, name, fg, bg)
|
||||
}
|
||||
|
||||
// NewErrorLogLevel creates an error-level log level without predefined colors.
|
||||
func NewErrorLogLevel(name string) LogLevel { return NewThresholdLogLevel(2, 30, name) }
|
||||
|
||||
// NewErrorLogLevelWithColors creates an error-level log level with ANSI colors.
|
||||
func NewErrorLogLevelWithColors(name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return NewThresholdLogLevelWithColors(2, 30, name, fg, bg)
|
||||
}
|
||||
|
||||
// NewFatalLogLevel creates a fatal-level log level without predefined colors.
|
||||
func NewFatalLogLevel(name string) LogLevel { return NewThresholdLogLevel(3, 40, name) }
|
||||
|
||||
// NewFatalLogLevelWithColors creates a fatal-level log level with ANSI colors.
|
||||
func NewFatalLogLevelWithColors(name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return NewThresholdLogLevelWithColors(3, 40, name, fg, bg)
|
||||
}
|
||||
|
||||
// NewDebugLogLevel creates a debug-level log level without predefined colors.
|
||||
func NewDebugLogLevel(name string) LogLevel { return NewThresholdLogLevel(4, 0, name) }
|
||||
|
||||
// NewDebugLogLevelWithColors creates a debug-level log level with ANSI colors.
|
||||
func NewDebugLogLevelWithColors(name string, fg FgColor, bg BgColor) LogLevel {
|
||||
return NewThresholdLogLevelWithColors(4, 0, name, fg, bg)
|
||||
}
|
||||
|
||||
// GetName returns the lowercase textual representation of the level.
|
||||
func (l *LogLevel) GetName() string { return l.t }
|
||||
|
||||
// SetFgColor sets the ANSI foreground color and clears other foreground color modes.
|
||||
// Deprecated: use SetForegroundColor. This method will be removed in v3.
|
||||
func (l *LogLevel) SetFgColor(color FgColor) *LogLevel {
|
||||
return l.SetForegroundColor(color)
|
||||
}
|
||||
|
||||
// GetFgColor returns the ANSI foreground color for the level.
|
||||
// Deprecated: use GetForegroundColor. This method will be removed in v3.
|
||||
func (l *LogLevel) GetFgColor() FgColor { return l.GetForegroundColor() }
|
||||
|
||||
// SetForegroundColor sets the ANSI foreground color and clears other foreground color modes.
|
||||
func (l *LogLevel) SetForegroundColor(color FgColor) *LogLevel {
|
||||
l.fg = color
|
||||
l.fg256 = 0
|
||||
l.fgRgb = nil
|
||||
return l
|
||||
}
|
||||
|
||||
// GetForegroundColor returns the ANSI foreground color for the level.
|
||||
func (l *LogLevel) GetForegroundColor() FgColor { return l.fg }
|
||||
|
||||
// SetForeground256Color sets the 256-color foreground and clears other foreground color modes.
|
||||
func (l *LogLevel) SetForeground256Color(color FgColor256) *LogLevel {
|
||||
l.fg = 0
|
||||
l.fg256 = color
|
||||
l.fgRgb = nil
|
||||
return l
|
||||
}
|
||||
|
||||
// GetForeground256Color returns the configured 256-color foreground value.
|
||||
func (l *LogLevel) GetForeground256Color() FgColor256 { return l.fg256 }
|
||||
|
||||
// SetForegroundRGB sets the RGB foreground color and clears other foreground color modes.
|
||||
func (l *LogLevel) SetForegroundRGB(r, g, b uint8) *LogLevel {
|
||||
l.fg = 0
|
||||
l.fg256 = 0
|
||||
l.fgRgb = FgColorRGB{r, g, b}
|
||||
return l
|
||||
}
|
||||
|
||||
// GetForegroundRGB returns the configured RGB foreground value.
|
||||
func (l *LogLevel) GetForegroundRGB() FgColorRGB { return l.fgRgb }
|
||||
|
||||
// SetBgColor sets the ANSI background color and clears other background color modes.
|
||||
// Deprecated: use SetBackgroundColor. This method will be removed in v3.
|
||||
func (l *LogLevel) SetBgColor(color BgColor) *LogLevel {
|
||||
return l.SetBackgroundColor(color)
|
||||
}
|
||||
|
||||
// GetBgColor returns the ANSI background color for the level.
|
||||
// Deprecated: use GetBackgroundColor. This method will be removed in v3.
|
||||
func (l *LogLevel) GetBgColor() BgColor { return l.GetBackgroundColor() }
|
||||
|
||||
// SetBackgroundColor sets the ANSI background color and clears other background color modes.
|
||||
func (l *LogLevel) SetBackgroundColor(color BgColor) *LogLevel {
|
||||
l.bg = color
|
||||
l.bg256 = 0
|
||||
l.bgRgb = nil
|
||||
return l
|
||||
}
|
||||
|
||||
// GetBackgroundColor returns the ANSI background color for the level.
|
||||
func (l *LogLevel) GetBackgroundColor() BgColor { return l.bg }
|
||||
|
||||
// SetBackground256Color sets the 256-color background and clears other background color modes.
|
||||
func (l *LogLevel) SetBackground256Color(color BgColor256) *LogLevel {
|
||||
l.bg = 0
|
||||
l.bg256 = color
|
||||
l.bgRgb = nil
|
||||
return l
|
||||
}
|
||||
|
||||
// GetBackground256Color returns the configured 256-color background value.
|
||||
func (l *LogLevel) GetBackground256Color() BgColor256 { return l.bg256 }
|
||||
|
||||
// SetBackgroundRGB sets the RGB background color and clears other background color modes.
|
||||
func (l *LogLevel) SetBackgroundRGB(r, g, b uint8) *LogLevel {
|
||||
l.bg = 0
|
||||
l.bg256 = 0
|
||||
l.bgRgb = BgColorRGB{r, g, b}
|
||||
return l
|
||||
}
|
||||
|
||||
// GetBackgroundRGB returns the configured RGB background value.
|
||||
func (l *LogLevel) GetBackgroundRGB() BgColorRGB { return l.bgRgb }
|
||||
|
||||
// AddAttribute appends an ANSI text attribute to the level.
|
||||
func (l *LogLevel) AddAttribute(a Attribute) *LogLevel {
|
||||
l.attrs = append(l.attrs, a)
|
||||
return l
|
||||
}
|
||||
|
||||
// RemoveAttribute removes all matching ANSI text attributes from the level.
|
||||
func (l *LogLevel) RemoveAttribute(a Attribute) *LogLevel {
|
||||
attrs := make([]Attribute, 0)
|
||||
for _, attr := range l.attrs {
|
||||
if attr != a {
|
||||
attrs = append(attrs, attr)
|
||||
}
|
||||
}
|
||||
l.attrs = attrs
|
||||
return l
|
||||
}
|
||||
|
||||
// SetAttributes replaces the level attributes with a copy of the provided slice.
|
||||
func (l *LogLevel) SetAttributes(a []Attribute) *LogLevel {
|
||||
attrs := make([]Attribute, len(a))
|
||||
copy(attrs, a)
|
||||
l.attrs = attrs
|
||||
return l
|
||||
}
|
||||
|
||||
// GetAttributes returns a copy of the configured ANSI text attributes.
|
||||
func (l *LogLevel) GetAttributes() []Attribute {
|
||||
attrs := make([]Attribute, len(l.attrs))
|
||||
copy(attrs, l.attrs)
|
||||
return attrs
|
||||
}
|
||||
|
||||
// SameLevel reports whether two log levels have the same severity index.
|
||||
// Deprecated: use SameThreshold for threshold-only comparisons or Equal for the
|
||||
// full level configuration. SameLevel remains severity-only for backward
|
||||
// compatibility and ignores threshold values.
|
||||
func (l *LogLevel) SameLevel(other LogLevel) bool {
|
||||
return l.n == other.n
|
||||
}
|
||||
|
||||
// SameThreshold reports whether two log levels have the same threshold value.
|
||||
func (l *LogLevel) SameThreshold(other LogLevel) bool {
|
||||
return l.th == other.th
|
||||
}
|
||||
|
||||
// Equal reports whether two log levels have identical configuration.
|
||||
func (l *LogLevel) Equal(other LogLevel) bool {
|
||||
if l.t != other.t || l.n != other.n || l.th != other.th {
|
||||
return false
|
||||
}
|
||||
if l.fg != other.fg || l.bg != other.bg {
|
||||
return false
|
||||
}
|
||||
|
||||
if l.fg256 != other.fg256 || l.bg256 != other.bg256 {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(l.attrs) != len(other.attrs) {
|
||||
return false
|
||||
}
|
||||
for i := range l.attrs {
|
||||
if l.attrs[i] != other.attrs[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if len(l.fgRgb) != len(other.fgRgb) {
|
||||
return false
|
||||
}
|
||||
for i := range l.fgRgb {
|
||||
if l.fgRgb[i] != other.fgRgb[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if len(l.bgRgb) != len(other.bgRgb) {
|
||||
return false
|
||||
}
|
||||
for i := range l.bgRgb {
|
||||
if l.bgRgb[i] != other.bgRgb[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,34 +1,13 @@
|
||||
package slog
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
)
|
||||
|
||||
type Logger struct {
|
||||
prefix string
|
||||
level LogLevel
|
||||
writers []LoggerWriter
|
||||
|
||||
printTraceback bool
|
||||
printTime bool
|
||||
jsonPretty bool
|
||||
}
|
||||
|
||||
type LogLevel struct {
|
||||
n uint8
|
||||
t string
|
||||
c color.Attribute
|
||||
}
|
||||
|
||||
func (l *LogLevel) GetName() string {
|
||||
return l.t
|
||||
}
|
||||
|
||||
// MethodTraceback describes a single stack frame attached to a log entry.
|
||||
type MethodTraceback struct {
|
||||
Method string `json:"method"`
|
||||
Filename string `json:"filename"`
|
||||
@@ -37,110 +16,170 @@ type MethodTraceback struct {
|
||||
FullPath string `json:"fullPath"`
|
||||
}
|
||||
|
||||
var (
|
||||
INFO = LogLevel{n: 0, t: "info", c: color.FgWhite}
|
||||
WARN = LogLevel{n: 1, t: "warn", c: color.FgHiYellow}
|
||||
ERROR = LogLevel{n: 2, t: "error", c: color.FgHiRed}
|
||||
FATAL = LogLevel{n: 3, t: "fatal", c: color.FgRed}
|
||||
DEBUG = LogLevel{n: 4, t: "debug", c: color.FgGreen}
|
||||
)
|
||||
// Logger routes log records to one or more configured writers.
|
||||
type Logger struct {
|
||||
prefix string
|
||||
level LogLevel
|
||||
|
||||
writers []LoggerWriter
|
||||
replacers []replacer
|
||||
|
||||
jsonPretty bool
|
||||
threshold bool
|
||||
}
|
||||
|
||||
// CreateLogger creates a logger with default settings.
|
||||
// Deprecated: use NewLogger. This method will be removed in v3.
|
||||
func CreateLogger() *Logger {
|
||||
return &Logger{
|
||||
prefix: "LOG",
|
||||
level: FATAL,
|
||||
printTraceback: false,
|
||||
printTime: true,
|
||||
}
|
||||
}
|
||||
|
||||
// NewLogger creates a logger with default settings.
|
||||
func NewLogger() *Logger {
|
||||
return &Logger{
|
||||
prefix: "LOG",
|
||||
level: FATAL,
|
||||
}
|
||||
}
|
||||
|
||||
// Prefix sets the record prefix and returns the logger for chaining.
|
||||
// Deprecated: use SetName. This method will be removed in v3.
|
||||
func (l *Logger) Prefix(prefix string) *Logger {
|
||||
l.prefix = prefix
|
||||
return l
|
||||
}
|
||||
|
||||
// SetName sets the record prefix and returns the logger for chaining.
|
||||
func (l *Logger) SetName(name string) *Logger {
|
||||
l.prefix = name
|
||||
return l
|
||||
}
|
||||
|
||||
// Level sets the maximum enabled level and returns the logger for chaining.
|
||||
// Deprecated: use SetLevel. This method will be removed in v3.
|
||||
func (l *Logger) Level(level LogLevel) *Logger {
|
||||
l.level = level
|
||||
return l
|
||||
}
|
||||
func (l *Logger) PrintTraceback(b bool) *Logger {
|
||||
l.printTraceback = b
|
||||
return l
|
||||
}
|
||||
func (l *Logger) PrintTime(b bool) *Logger {
|
||||
l.printTime = b
|
||||
|
||||
// SetLevel sets the maximum enabled level and returns the logger for chaining.
|
||||
func (l *Logger) SetLevel(level LogLevel) *Logger {
|
||||
l.level = level
|
||||
return l
|
||||
}
|
||||
|
||||
// JsonPretty enables or disables indented JSON output for JSON writers created by the logger.
|
||||
// Deprecated: use SetJSONPretty. This method will be removed in v3.
|
||||
func (l *Logger) JsonPretty(b bool) *Logger {
|
||||
l.jsonPretty = b
|
||||
return l
|
||||
}
|
||||
|
||||
// SetJSONPretty enables or disables indented output for JSON writers created by the logger.
|
||||
func (l *Logger) SetJSONPretty(b bool) *Logger {
|
||||
l.jsonPretty = b
|
||||
return l
|
||||
}
|
||||
|
||||
// SetThresholdMode switches Logger.Print filtering from legacy severity-index
|
||||
// ordering to LogLevel threshold ordering.
|
||||
func (l *Logger) SetThresholdMode(b bool) *Logger {
|
||||
l.threshold = b
|
||||
return l
|
||||
}
|
||||
|
||||
// AddWriters appends multiple writers to the logger.
|
||||
func (l *Logger) AddWriters(writers ...LoggerWriter) *Logger {
|
||||
l.writers = append(l.writers, writers...)
|
||||
return l
|
||||
}
|
||||
|
||||
// AddWriter appends a single writer to the logger.
|
||||
// Deprecated: use AddWriters. This method will be removed in v3.
|
||||
func (l *Logger) AddWriter(writer LoggerWriter) *Logger {
|
||||
l.writers = append(l.writers, writer)
|
||||
return l
|
||||
}
|
||||
func (l *Logger) Close() error {
|
||||
for _, writer := range l.writers {
|
||||
err := writer.Close()
|
||||
if err != nil {
|
||||
l.Error(err)
|
||||
|
||||
// AddReplacer appends a message replacer and returns the logger for chaining.
|
||||
//
|
||||
// Replacement rules are applied before records are passed to writers. Empty old
|
||||
// values are ignored because replacing an empty string would insert the
|
||||
// replacement between every UTF-8 sequence.
|
||||
func (l *Logger) AddReplacer(old, new string) *Logger {
|
||||
if old == "" {
|
||||
return l
|
||||
}
|
||||
}
|
||||
return nil
|
||||
r := replacer{old: old, new: new}
|
||||
l.replacers = append(l.replacers, r)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Logger) CreateTextWriter(w io.Writer) *LoggerTextWriter {
|
||||
return CreateTextWriter(w, l.printTraceback, l.printTime)
|
||||
}
|
||||
func (l *Logger) CreateTextStdoutWriter() *LoggerTextWriter {
|
||||
return CreateTextStdoutWriter(l.printTraceback, l.printTime)
|
||||
// Close closes all owned writers and returns a joined error, if any.
|
||||
func (l *Logger) Close() error {
|
||||
var errs []error
|
||||
for _, writer := range l.writers {
|
||||
if writer == nil {
|
||||
continue
|
||||
}
|
||||
err := writer.Close()
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
l.writers = nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// CreateTextWriter wraps an external writer with the logger text settings.
|
||||
func (l *Logger) CreateTextWriter(w io.Writer) *LoggerTextWriter { return CreateTextWriter(w) }
|
||||
|
||||
// CreateTextStdoutWriter creates a non-owning text writer for os.Stdout.
|
||||
func (l *Logger) CreateTextStdoutWriter() *LoggerTextWriter { return CreateTextStdoutWriter() }
|
||||
|
||||
// CreateTextFileWriter creates an owning text writer for a file.
|
||||
func (l *Logger) CreateTextFileWriter(filename string) (*LoggerTextWriter, error) {
|
||||
return CreateTextFileWriter(filename, l.printTraceback, l.printTime)
|
||||
return CreateTextFileWriter(filename)
|
||||
}
|
||||
|
||||
// CreateJsonWriter wraps an external writer with the logger JSON settings.
|
||||
func (l *Logger) CreateJsonWriter(w io.Writer) *LoggerJsonWriter {
|
||||
return CreateJsonWriter(w, l.jsonPretty)
|
||||
}
|
||||
|
||||
// CreateJsonStdoutWriter creates a non-owning JSON writer for os.Stdout.
|
||||
func (l *Logger) CreateJsonStdoutWriter() *LoggerJsonWriter {
|
||||
return CreateJsonStdoutWriter(l.jsonPretty)
|
||||
}
|
||||
|
||||
// CreateJsonFileWriter creates an owning JSON writer for a file.
|
||||
func (l *Logger) CreateJsonFileWriter(filename string) (*LoggerJsonWriter, error) {
|
||||
return CreateJsonFileWriter(filename, l.jsonPretty)
|
||||
}
|
||||
|
||||
func FormatTime(t time.Time) string {
|
||||
return fmt.Sprintf("%02d.%02d.%02d %02d:%02d:%02d", t.Day(), t.Month(), t.Year(), t.Hour(), t.Minute(), t.Second())
|
||||
type replacer struct {
|
||||
old string
|
||||
new string
|
||||
}
|
||||
func FormatTraceback(mt *MethodTraceback) string {
|
||||
return fmt.Sprintf("%s:%s:%d", mt.Filename, mt.Method, mt.Line)
|
||||
}
|
||||
func FormatFullTraceback(tracebacks []*MethodTraceback) string {
|
||||
formatted := make([]string, 0)
|
||||
for _, tb := range tracebacks {
|
||||
formatted = append(formatted, FormatTraceback(tb))
|
||||
}
|
||||
return strings.Join(formatted, "->")
|
||||
}
|
||||
func BuildString(level LogLevel, prefix string, printTime, printTraceback bool, m ...any) string {
|
||||
args := []string{
|
||||
fmt.Sprintf("[%s]", prefix),
|
||||
fmt.Sprintf("[%s]", strings.ToUpper(level.t)),
|
||||
}
|
||||
|
||||
if printTraceback {
|
||||
args = append(args, fmt.Sprintf("[%s]", FormatTraceback(getTraceback())))
|
||||
func (r replacer) replace(s string) string { return strings.ReplaceAll(s, r.old, r.new) }
|
||||
func (l *Logger) replace(s string) string {
|
||||
out := s
|
||||
for _, repl := range l.replacers {
|
||||
out = repl.replace(out)
|
||||
}
|
||||
|
||||
if printTime {
|
||||
args = append(args, fmt.Sprintf("[%s]", FormatTime(time.Now())))
|
||||
return out
|
||||
}
|
||||
func (l *Logger) replaceAll(messages ...any) []any {
|
||||
if len(l.replacers) == 0 {
|
||||
return messages
|
||||
}
|
||||
|
||||
msg := Map(m, func(el any) string {
|
||||
return fmt.Sprintf("%v", el)
|
||||
})
|
||||
s := fmt.Sprintf("%s %s", strings.Join(args, " "), strings.Join(msg, " "))
|
||||
return s
|
||||
out := make([]any, len(messages))
|
||||
for i, msg := range messages {
|
||||
out[i] = l.replace(fmt.Sprint(msg))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
+695
@@ -0,0 +1,695 @@
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type stubLoggerWriter struct {
|
||||
printErr error
|
||||
closeErr error
|
||||
printCalls int
|
||||
closeCalls int
|
||||
messages []any
|
||||
}
|
||||
|
||||
func (w *stubLoggerWriter) Formatter() *Formatter {
|
||||
return &Formatter{}
|
||||
}
|
||||
func (w *stubLoggerWriter) Close() error {
|
||||
w.closeCalls++
|
||||
return w.closeErr
|
||||
}
|
||||
|
||||
func (w *stubLoggerWriter) Write(p []byte) (int, error) {
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *stubLoggerWriter) Print(_ LogLevel, _ string, _ []*MethodTraceback, messages ...any) error {
|
||||
w.printCalls++
|
||||
w.messages = append([]any(nil), messages...)
|
||||
return w.printErr
|
||||
}
|
||||
|
||||
func TestLoggerCloseReturnsJoinedErrorsWithoutRelogging(t *testing.T) {
|
||||
firstErr := errors.New("first close failed")
|
||||
secondErr := errors.New("second close failed")
|
||||
first := &stubLoggerWriter{closeErr: firstErr}
|
||||
second := &stubLoggerWriter{closeErr: secondErr}
|
||||
|
||||
logger := CreateLogger().AddWriters(first, second)
|
||||
err := logger.Close()
|
||||
if !errors.Is(err, firstErr) {
|
||||
t.Fatalf("Close() error should include first writer error, got %v", err)
|
||||
}
|
||||
if !errors.Is(err, secondErr) {
|
||||
t.Fatalf("Close() error should include second writer error, got %v", err)
|
||||
}
|
||||
if first.printCalls != 0 || second.printCalls != 0 {
|
||||
t.Fatalf("Close() should not log through writers again, got print calls first=%d second=%d", first.printCalls, second.printCalls)
|
||||
}
|
||||
if first.closeCalls != 1 || second.closeCalls != 1 {
|
||||
t.Fatalf("Close() should close each writer once, got close calls first=%d second=%d", first.closeCalls, second.closeCalls)
|
||||
}
|
||||
if err := logger.Close(); err != nil {
|
||||
t.Fatalf("second Close() should be a no-op, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerPrintDoesNotRecurseOnWriterError(t *testing.T) {
|
||||
oldStderr := os.Stderr
|
||||
stderrFile, err := os.CreateTemp(t.TempDir(), "stderr")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTemp() error = %v", err)
|
||||
}
|
||||
os.Stderr = stderrFile
|
||||
t.Cleanup(func() {
|
||||
os.Stderr = oldStderr
|
||||
_ = stderrFile.Close()
|
||||
})
|
||||
|
||||
bad := &stubLoggerWriter{printErr: errors.New("print failed")}
|
||||
good := &stubLoggerWriter{}
|
||||
|
||||
logger := CreateLogger().AddWriters(bad, good)
|
||||
logger.Error("boom")
|
||||
|
||||
if bad.printCalls != 1 {
|
||||
t.Fatalf("bad writer should be called once, got %d", bad.printCalls)
|
||||
}
|
||||
if good.printCalls != 1 {
|
||||
t.Fatalf("good writer should be called once, got %d", good.printCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerPreservesMessageTypesWithoutReplacers(t *testing.T) {
|
||||
writer := &stubLoggerWriter{}
|
||||
logger := CreateLogger().AddWriter(writer)
|
||||
|
||||
logger.Error("status", 500)
|
||||
|
||||
if len(writer.messages) != 2 {
|
||||
t.Fatalf("writer should receive two messages, got %d", len(writer.messages))
|
||||
}
|
||||
if _, ok := writer.messages[1].(int); !ok {
|
||||
t.Fatalf("writer should receive original int message type, got %T", writer.messages[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerPrintfFormatsMessage(t *testing.T) {
|
||||
writer := &stubLoggerWriter{}
|
||||
logger := CreateLogger().
|
||||
SetLevel(DEBUG).
|
||||
AddWriter(writer)
|
||||
|
||||
logger.Printf(INFO, "status=%d %s", 200, "ok")
|
||||
|
||||
if writer.printCalls != 1 {
|
||||
t.Fatalf("Printf() should write once, got %d calls", writer.printCalls)
|
||||
}
|
||||
if len(writer.messages) != 1 {
|
||||
t.Fatalf("Printf() should produce one formatted message, got %d parts", len(writer.messages))
|
||||
}
|
||||
if got, ok := writer.messages[0].(string); !ok || got != "status=200 ok" {
|
||||
t.Fatalf("Printf() should format message, got %#v", writer.messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerUsesSeverityOrderingWhenThresholdModeIsDisabled(t *testing.T) {
|
||||
writer := &stubLoggerWriter{}
|
||||
logger := CreateLogger().
|
||||
SetLevel(NewThresholdLogLevel(1, 0, "warn")).
|
||||
AddWriter(writer)
|
||||
|
||||
logger.Print(NewThresholdLogLevel(0, 100, "info"))
|
||||
logger.Print(NewThresholdLogLevel(2, 0, "error"))
|
||||
|
||||
if writer.printCalls != 1 {
|
||||
t.Fatalf("severity mode should allow only lower-or-equal severity levels, got %d writes", writer.printCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerUsesThresholdOrderingWhenThresholdModeIsEnabled(t *testing.T) {
|
||||
writer := &stubLoggerWriter{}
|
||||
logger := CreateLogger().
|
||||
SetLevel(NewThresholdLogLevel(4, 20, "custom")).
|
||||
SetThresholdMode(true).
|
||||
AddWriter(writer)
|
||||
|
||||
logger.Print(NewThresholdLogLevel(4, 10, "debug"))
|
||||
logger.Print(NewThresholdLogLevel(0, 30, "info"))
|
||||
|
||||
if writer.printCalls != 1 {
|
||||
t.Fatalf("threshold mode should allow only entries at or below the configured threshold, got %d writes", writer.printCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedLevelMethodKeepsLegacySeverityBehavior(t *testing.T) {
|
||||
writer := &stubLoggerWriter{}
|
||||
logger := CreateLogger().
|
||||
Level(FATAL).
|
||||
AddWriter(writer)
|
||||
|
||||
logger.Print(INFO, "info")
|
||||
logger.Print(WARN, "warn")
|
||||
logger.Print(ERROR, "error")
|
||||
logger.Print(FATAL, "fatal")
|
||||
logger.Print(DEBUG, "debug")
|
||||
|
||||
if writer.printCalls != 4 {
|
||||
t.Fatalf("Level(FATAL) should keep legacy behavior and allow INFO/WARN/ERROR/FATAL only, got %d writes", writer.printCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameLevelIgnoresThresholdDifferencesForCompatibility(t *testing.T) {
|
||||
legacy := NewLogLevel(1, "warn")
|
||||
threshold := NewThresholdLogLevel(1, 20, "warn")
|
||||
|
||||
if !legacy.SameLevel(threshold) {
|
||||
t.Fatalf("SameLevel() should continue comparing only severity index")
|
||||
}
|
||||
if legacy.Equal(threshold) {
|
||||
t.Fatalf("Equal() should distinguish levels with different threshold configuration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameThresholdComparesOnlyThresholdValue(t *testing.T) {
|
||||
first := NewThresholdLogLevel(1, 20, "warn")
|
||||
second := NewThresholdLogLevel(9, 20, "custom")
|
||||
third := NewThresholdLogLevel(1, 30, "warn")
|
||||
|
||||
if !first.SameThreshold(second) {
|
||||
t.Fatalf("SameThreshold() should ignore severity and compare threshold only")
|
||||
}
|
||||
if first.SameThreshold(third) {
|
||||
t.Fatalf("SameThreshold() should detect different threshold values")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelForMethodReturnsExpectedLevels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
want LogLevel
|
||||
}{
|
||||
{name: "get", method: http.MethodGet, want: HTTPGetLevel},
|
||||
{name: "head", method: http.MethodHead, want: HTTPHeadLevel},
|
||||
{name: "post", method: http.MethodPost, want: HTTPPostLevel},
|
||||
{name: "put", method: http.MethodPut, want: HTTPPutLevel},
|
||||
{name: "patch", method: http.MethodPatch, want: HTTPPatchLevel},
|
||||
{name: "delete", method: http.MethodDelete, want: HTTPDeleteLevel},
|
||||
{name: "options", method: http.MethodOptions, want: HTTPOptionsLevel},
|
||||
{name: "connect", method: http.MethodConnect, want: HTTPConnectLevel},
|
||||
{name: "trace", method: http.MethodTrace, want: HTTPTraceLevel},
|
||||
{name: "unknown", method: "PROPFIND", want: HTTPUnknownLevel},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := LogLevelForMethod(tt.method)
|
||||
if got.n != tt.want.n || got.t != tt.want.t || got.fg != tt.want.fg || got.bg != tt.want.bg {
|
||||
t.Fatalf("LogLevelForMethod(%q) = %#v, want %#v", tt.method, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLevelConstructorsSetExpectedSeverity(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
got LogLevel
|
||||
want LogLevel
|
||||
wantTh uint8
|
||||
}{
|
||||
{name: "info", got: NewInfoLogLevel("custom"), want: INFO, wantTh: 10},
|
||||
{name: "warn", got: NewWarnLogLevel("custom"), want: WARN, wantTh: 20},
|
||||
{name: "error", got: NewErrorLogLevel("custom"), want: ERROR, wantTh: 30},
|
||||
{name: "fatal", got: NewFatalLogLevel("custom"), want: FATAL, wantTh: 40},
|
||||
{name: "debug", got: NewDebugLogLevel("custom"), want: DEBUG, wantTh: 0},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.got.n != tt.want.n {
|
||||
t.Fatalf("%s severity = %d, want %d", tt.name, tt.got.n, tt.want.n)
|
||||
}
|
||||
if tt.got.th != tt.wantTh {
|
||||
t.Fatalf("%s threshold = %d, want %d", tt.name, tt.got.th, tt.wantTh)
|
||||
}
|
||||
if tt.got.GetName() != "custom" {
|
||||
t.Fatalf("%s constructor should preserve name, got %q", tt.name, tt.got.GetName())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLevelConstructorsWithColorsSetExpectedFields(t *testing.T) {
|
||||
info := NewInfoLogLevelWithColors("info-custom", FgBlue, BgYellow)
|
||||
if info.n != INFO.n || info.GetName() != "info-custom" || info.fg != FgBlue || info.bg != BgYellow {
|
||||
t.Fatalf("NewInfoLogLevelWithColors() = %#v", info)
|
||||
}
|
||||
|
||||
warn := NewWarnLogLevelWithColors("warn-custom", FgMagenta, BgCyan)
|
||||
if warn.n != WARN.n || warn.GetName() != "warn-custom" || warn.fg != FgMagenta || warn.bg != BgCyan {
|
||||
t.Fatalf("NewWarnLogLevelWithColors() = %#v", warn)
|
||||
}
|
||||
|
||||
errLevel := NewErrorLogLevelWithColors("error-custom", FgRed, BgWhite)
|
||||
if errLevel.n != ERROR.n || errLevel.GetName() != "error-custom" || errLevel.fg != FgRed || errLevel.bg != BgWhite {
|
||||
t.Fatalf("NewErrorLogLevelWithColors() = %#v", errLevel)
|
||||
}
|
||||
|
||||
fatal := NewFatalLogLevelWithColors("fatal-custom", FgHiRed, BgBlack)
|
||||
if fatal.n != FATAL.n || fatal.GetName() != "fatal-custom" || fatal.fg != FgHiRed || fatal.bg != BgBlack {
|
||||
t.Fatalf("NewFatalLogLevelWithColors() = %#v", fatal)
|
||||
}
|
||||
|
||||
debug := NewDebugLogLevelWithColors("debug-custom", FgGreen, BgDefault)
|
||||
if debug.n != DEBUG.n || debug.GetName() != "debug-custom" || debug.fg != FgGreen || debug.bg != BgDefault {
|
||||
t.Fatalf("NewDebugLogLevelWithColors() = %#v", debug)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTextWriterCloseOnNonCloserIsNoOp(t *testing.T) {
|
||||
writer := CreateTextWriter(&bytes.Buffer{})
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTextWriterDoesNotCloseExternalCloser(t *testing.T) {
|
||||
file, err := os.CreateTemp(t.TempDir(), "text-writer")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTemp() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = file.Close()
|
||||
})
|
||||
|
||||
writer := CreateTextWriter(file)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
if _, err := file.WriteString("still open"); err != nil {
|
||||
t.Fatalf("CreateTextWriter() should not close external writers, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateJsonWriterCloseOnNonCloserIsNoOp(t *testing.T) {
|
||||
writer := CreateJsonWriter(&bytes.Buffer{}, false)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateJsonWriterDoesNotCloseExternalCloser(t *testing.T) {
|
||||
file, err := os.CreateTemp(t.TempDir(), "json-writer")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTemp() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = file.Close()
|
||||
})
|
||||
|
||||
writer := CreateJsonWriter(file, false)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
if _, err := file.WriteString("still open"); err != nil {
|
||||
t.Fatalf("CreateJsonWriter() should not close external writers, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonWriterPrintAllowsEmptyMessages(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := CreateJsonWriter(&buf, false)
|
||||
|
||||
if err := writer.Print(INFO, "TEST", nil); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
|
||||
var message LoggerJsonMessage
|
||||
if err := json.Unmarshal(buf.Bytes(), &message); err != nil {
|
||||
t.Fatalf("json.Unmarshal() error = %v", err)
|
||||
}
|
||||
if message.Message != "" {
|
||||
t.Fatalf("message should be empty, got %q", message.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonWriterPrintPreservesTrailingNewlineSemantic(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := CreateJsonWriter(&buf, false)
|
||||
|
||||
if err := writer.Print(INFO, "TEST", nil, "hello\n"); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
|
||||
data := buf.Bytes()
|
||||
if !bytes.HasSuffix(data, []byte("\n")) {
|
||||
t.Fatalf("JSON output should end with newline, got %q", data)
|
||||
}
|
||||
|
||||
var message LoggerJsonMessage
|
||||
if err := json.Unmarshal(bytes.TrimSuffix(data, []byte("\n")), &message); err != nil {
|
||||
t.Fatalf("json.Unmarshal() error = %v", err)
|
||||
}
|
||||
if message.Message != "hello" {
|
||||
t.Fatalf("message should not include trailing newline, got %q", message.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextWriterPrintlnDoesNotLeaveTrailingMessageSeparator(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
formatter := NewFormatter().
|
||||
SetFormat("%m (%S)").
|
||||
SetColorOutput(false)
|
||||
writer := CreateTextWriter(&buf).SetFormatter(formatter)
|
||||
|
||||
if err := writer.Print(DEBUG, "TEST", nil, "debug details", "\n"); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
|
||||
got := strings.TrimSuffix(buf.String(), "\n")
|
||||
if got != "debug details (%S)" {
|
||||
t.Fatalf("println newline marker should not leave trailing message separator, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextWriterPrintlnDoesNotLeaveTrailingMessageSeparatorAfterReplacement(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
formatter := NewFormatter().
|
||||
SetFormat("%m (%S)").
|
||||
SetColorOutput(false)
|
||||
writer := CreateTextWriter(&buf).SetFormatter(formatter)
|
||||
logger := CreateLogger().
|
||||
SetLevel(DEBUG).
|
||||
AddWriter(writer).
|
||||
AddReplacer("details", "details")
|
||||
|
||||
logger.Debugln("debug details")
|
||||
|
||||
got := strings.TrimSuffix(buf.String(), "\n")
|
||||
if got != "debug details (%S)" {
|
||||
t.Fatalf("println newline marker should not leave trailing message separator after replacements, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonWriterPrintlnDoesNotLeaveTrailingMessageSeparator(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := CreateJsonWriter(&buf, false)
|
||||
|
||||
if err := writer.Print(INFO, "TEST", nil, "hello", "\n"); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
|
||||
var message LoggerJsonMessage
|
||||
if err := json.Unmarshal(bytes.TrimSuffix(buf.Bytes(), []byte("\n")), &message); err != nil {
|
||||
t.Fatalf("json.Unmarshal() error = %v", err)
|
||||
}
|
||||
if message.Message != "hello" {
|
||||
t.Fatalf("message should not include trailing separator from newline marker, got %q", message.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelForegroundSettersOverridePreviousColorMode(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
formatter := NewFormatter()
|
||||
|
||||
level.SetFgColor(FgRed)
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, FgRed.String()) {
|
||||
t.Fatalf("expected plain foreground color prefix %q, got %q", FgRed.String(), got)
|
||||
}
|
||||
|
||||
level.SetForeground256Color(FgColor256(123))
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, FgColor256(123).String()) {
|
||||
t.Fatalf("expected 256-color foreground prefix %q, got %q", FgColor256(123).String(), got)
|
||||
}
|
||||
|
||||
level.SetForegroundRGB(1, 2, 3)
|
||||
expectedRGB := NewFgColorRGB(1, 2, 3).String()
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, expectedRGB) {
|
||||
t.Fatalf("expected RGB foreground prefix %q, got %q", expectedRGB, got)
|
||||
}
|
||||
|
||||
level.SetFgColor(FgBlue)
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, FgBlue.String()) {
|
||||
t.Fatalf("expected last plain foreground color to win with prefix %q, got %q", FgBlue.String(), got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelBackgroundSettersOverridePreviousColorMode(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
formatter := NewFormatter()
|
||||
|
||||
level.SetBgColor(BgRed)
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, BgRed.String()) {
|
||||
t.Fatalf("expected plain background color prefix %q, got %q", BgRed.String(), got)
|
||||
}
|
||||
|
||||
level.SetBackground256Color(BgColor256(123))
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, BgColor256(123).String()) {
|
||||
t.Fatalf("expected 256-color background prefix %q, got %q", BgColor256(123).String(), got)
|
||||
}
|
||||
|
||||
level.SetBackgroundRGB(1, 2, 3)
|
||||
expectedRGB := NewBgColorRGB(1, 2, 3).String()
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, expectedRGB) {
|
||||
t.Fatalf("expected RGB background prefix %q, got %q", expectedRGB, got)
|
||||
}
|
||||
|
||||
level.SetBgColor(BgBlue)
|
||||
if got := formatter.ColorizeString("x", level); !strings.HasPrefix(got, BgBlue.String()) {
|
||||
t.Fatalf("expected last plain background color to win with prefix %q, got %q", BgBlue.String(), got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelAttributesAffectColorizedOutput(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
level.AddAttribute(Italic).AddAttribute(Bold)
|
||||
|
||||
got := NewFormatter().ColorizeString("x", level)
|
||||
if !strings.Contains(got, Italic.String()) {
|
||||
t.Fatalf("expected italic attribute in colorized output, got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, Bold.String()) {
|
||||
t.Fatalf("expected bold attribute in colorized output, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelRemoveAttributeRemovesAllMatches(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
level.AddAttribute(Bold).AddAttribute(Italic).AddAttribute(Bold)
|
||||
|
||||
level.RemoveAttribute(Bold)
|
||||
|
||||
got := level.GetAttributes()
|
||||
if len(got) != 1 || got[0] != Italic {
|
||||
t.Fatalf("expected only italic attribute to remain, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelSetAttributesCopiesInputSlice(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
attrs := []Attribute{Bold, Italic}
|
||||
|
||||
level.SetAttributes(attrs)
|
||||
attrs[0] = Underline
|
||||
|
||||
got := level.GetAttributes()
|
||||
if len(got) != 2 || got[0] != Bold || got[1] != Italic {
|
||||
t.Fatalf("expected SetAttributes to copy input slice, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelGetAttributesReturnsCopy(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
level.SetAttributes([]Attribute{Bold, Italic})
|
||||
|
||||
got := level.GetAttributes()
|
||||
got[0] = Underline
|
||||
|
||||
again := level.GetAttributes()
|
||||
if len(again) != 2 || again[0] != Bold || again[1] != Italic {
|
||||
t.Fatalf("expected GetAttributes to return a copy, got %#v", again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelDeprecatedForegroundAccessorsRemainCompatible(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
|
||||
level.SetFgColor(FgBlue)
|
||||
if got := level.GetFgColor(); got != FgBlue {
|
||||
t.Fatalf("expected deprecated foreground accessors to round-trip %v, got %v", FgBlue, got)
|
||||
}
|
||||
|
||||
level.SetForegroundColor(FgRed)
|
||||
if got := level.GetFgColor(); got != FgRed {
|
||||
t.Fatalf("expected deprecated getter to reflect new foreground setter, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogLevelDeprecatedBackgroundAccessorsRemainCompatible(t *testing.T) {
|
||||
level := NewLogLevel(0, "custom")
|
||||
|
||||
level.SetBgColor(BgBlue)
|
||||
if got := level.GetBgColor(); got != BgBlue {
|
||||
t.Fatalf("expected deprecated background accessors to round-trip %v, got %v", BgBlue, got)
|
||||
}
|
||||
|
||||
level.SetBackgroundColor(BgRed)
|
||||
if got := level.GetBgColor(); got != BgRed {
|
||||
t.Fatalf("expected deprecated getter to reflect new background setter, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatterHandlesEmptyTracebackPlaceholders(t *testing.T) {
|
||||
formatter := NewFormatter().
|
||||
SetFormat("%m|%b|%B|%M|%f|%n|%s|%p")
|
||||
|
||||
got := formatter.FormatMessage(INFO, "TEST", nil, "hello")
|
||||
if got != "hello|||||||" {
|
||||
t.Fatalf("empty traceback placeholders should be empty, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatterDoesNotInterpretPlaceholdersInsideMessages(t *testing.T) {
|
||||
formatter := NewFormatter().
|
||||
SetFormat("%L:%m")
|
||||
|
||||
message := "literal %L %s %p"
|
||||
got := formatter.FormatMessage(INFO, "TEST", nil, message)
|
||||
if got != "INFO:literal %L %s %p" {
|
||||
t.Fatalf("message placeholder-looking text should stay literal, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFormatterDoesNotMutateDefaultFormatter(t *testing.T) {
|
||||
formatter := NewFormatter()
|
||||
formatter.SetFormat("custom")
|
||||
|
||||
if DefaultTextFormatter.Format == "custom" {
|
||||
t.Fatal("NewFormatter() should return a copy, not mutate DefaultTextFormatter")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextWriterColorOutputHonorsColorOnlyStdoutFalse(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
formatter := NewFormatter().
|
||||
SetFormat("%m").
|
||||
SetColorOutput(true).
|
||||
SetColorOnlyStdout(false)
|
||||
writer := CreateTextWriter(&buf).SetFormatter(formatter)
|
||||
|
||||
if err := writer.Print(INFO, "TEST", nil, "hello"); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "\x1b[") {
|
||||
t.Fatalf("ColorOnlyStdout(false) should allow color for external writers, got %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextWriterColorOutputCanBeDisabled(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
formatter := NewFormatter().
|
||||
SetFormat("%m").
|
||||
SetColorOutput(false).
|
||||
SetColorOnlyStdout(false)
|
||||
writer := CreateTextWriter(&buf).SetFormatter(formatter)
|
||||
|
||||
if err := writer.Print(INFO, "TEST", nil, "hello"); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
if strings.Contains(buf.String(), "\x1b[") {
|
||||
t.Fatalf("SetColorOutput(false) should disable color output, got %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTextStdoutWriterDoesNotCloseStdout(t *testing.T) {
|
||||
stdoutFile := swapStdout(t)
|
||||
|
||||
writer := CreateTextStdoutWriter()
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
if _, err := stdoutFile.WriteString("still open"); err != nil {
|
||||
t.Fatalf("stdout writer Close() should not close stdout, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateJsonStdoutWriterDoesNotCloseStdout(t *testing.T) {
|
||||
stdoutFile := swapStdout(t)
|
||||
|
||||
writer := CreateJsonStdoutWriter(false)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close() error = %v", err)
|
||||
}
|
||||
if _, err := stdoutFile.WriteString("still open"); err != nil {
|
||||
t.Fatalf("stdout writer Close() should not close stdout, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFullTracebackSkipsRuntimeAndSneklogFrames(t *testing.T) {
|
||||
tracebacks := captureTracebackForTest()
|
||||
if len(tracebacks) == 0 {
|
||||
t.Fatal("expected at least one traceback frame")
|
||||
}
|
||||
|
||||
first := tracebacks[0]
|
||||
if first.Method != "captureTracebackForTest" {
|
||||
t.Fatalf("first frame should be the nearest user frame, got %s", first.Method)
|
||||
}
|
||||
for _, tb := range tracebacks {
|
||||
if strings.HasPrefix(tb.Signature, "runtime.") {
|
||||
t.Fatalf("runtime frame should be filtered out, got %s", tb.Signature)
|
||||
}
|
||||
if _, ok := internalTracebackMethods[tb.Method]; ok {
|
||||
t.Fatalf("internal sneklog frame should be filtered out, got %s", tb.Signature)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTracebackReturnsNearestUserFrame(t *testing.T) {
|
||||
tb := captureSingleTracebackForTest()
|
||||
if tb == nil {
|
||||
t.Fatal("expected traceback frame")
|
||||
}
|
||||
if tb.Method != "captureSingleTracebackForTest" {
|
||||
t.Fatalf("expected nearest user frame, got %s", tb.Method)
|
||||
}
|
||||
if strings.HasPrefix(tb.Signature, "runtime.") {
|
||||
t.Fatalf("runtime frame should be filtered out, got %s", tb.Signature)
|
||||
}
|
||||
if _, ok := internalTracebackMethods[tb.Method]; ok {
|
||||
t.Fatalf("internal sneklog frame should be filtered out, got %s", tb.Signature)
|
||||
}
|
||||
}
|
||||
|
||||
func swapStdout(t *testing.T) *os.File {
|
||||
t.Helper()
|
||||
|
||||
oldStdout := os.Stdout
|
||||
stdoutFile, err := os.CreateTemp(t.TempDir(), "stdout")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTemp() error = %v", err)
|
||||
}
|
||||
os.Stdout = stdoutFile
|
||||
t.Cleanup(func() {
|
||||
os.Stdout = oldStdout
|
||||
_ = stdoutFile.Close()
|
||||
})
|
||||
return stdoutFile
|
||||
}
|
||||
|
||||
func captureTracebackForTest() []*MethodTraceback {
|
||||
return getFullTraceback(0)
|
||||
}
|
||||
|
||||
func captureSingleTracebackForTest() *MethodTraceback {
|
||||
return getTraceback()
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package sneklog
|
||||
|
||||
import "strings"
|
||||
|
||||
// Predefined strftime-like time layouts.
|
||||
const (
|
||||
Layout = "%m/%d %I:%M:%S%p '%y %z"
|
||||
ANSIC = "%a %b %e %H:%M:%S %Y"
|
||||
UnixDate = "%a %b %e %H:%M:%S %Z %Y"
|
||||
RubyDate = "%a %b %d %H:%M:%S %z %Y"
|
||||
|
||||
RFC822 = "%d %b %y %H:%M %Z"
|
||||
RFC822Z = "%d %b %y %H:%M %z"
|
||||
RFC850 = "%A, %d-%b-%y %H:%M:%S %Z"
|
||||
RFC1123 = "%a, %d %b %Y %H:%M:%S %Z"
|
||||
RFC1123Z = "%a, %d %b %Y %H:%M:%S %z"
|
||||
RFC3339 = "%Y-%m-%dT%H:%M:%S%:z"
|
||||
RFC3339Nano = "%Y-%m-%dT%H:%M:%S%#N%:z"
|
||||
Kitchen = "%-I:%M%p"
|
||||
|
||||
Stamp = "%b %e %H:%M:%S"
|
||||
StampMilli = "%b %e %H:%M:%S.%L"
|
||||
StampMicro = "%b %e %H:%M:%S.%f"
|
||||
StampNano = "%b %e %H:%M:%S.%N"
|
||||
DateTime = "%Y-%m-%d %H:%M:%S"
|
||||
DateOnly = "%Y-%m-%d"
|
||||
TimeOnly = "%H:%M:%S"
|
||||
)
|
||||
|
||||
type rule struct {
|
||||
strf string
|
||||
goLayout string
|
||||
}
|
||||
|
||||
var strftimeToGoRules = []rule{
|
||||
// Long/special tokens first.
|
||||
{"%::z", "Z07:00:00"},
|
||||
{"%:::z", "Z07"},
|
||||
{"%:z", "Z07:00"},
|
||||
|
||||
{"%#N", ".999999999"},
|
||||
{"%#f", ".999999"},
|
||||
{"%#L", ".999"},
|
||||
|
||||
{"%-m", "1"},
|
||||
{"%#m", "1"},
|
||||
{"%-d", "2"},
|
||||
{"%#d", "2"},
|
||||
{"%-H", "15"},
|
||||
{"%#H", "15"},
|
||||
{"%-I", "3"},
|
||||
{"%#I", "3"},
|
||||
{"%-M", "4"},
|
||||
{"%#M", "4"},
|
||||
{"%-S", "5"},
|
||||
{"%#S", "5"},
|
||||
|
||||
{"%%", "%"},
|
||||
|
||||
{"%Y", "2006"},
|
||||
{"%y", "06"},
|
||||
|
||||
{"%B", "January"},
|
||||
{"%b", "Jan"},
|
||||
{"%h", "Jan"},
|
||||
{"%m", "01"},
|
||||
|
||||
{"%d", "02"},
|
||||
{"%e", "_2"},
|
||||
|
||||
{"%A", "Monday"},
|
||||
{"%a", "Mon"},
|
||||
|
||||
{"%H", "15"},
|
||||
{"%I", "03"},
|
||||
{"%M", "04"},
|
||||
{"%S", "05"},
|
||||
|
||||
{"%p", "PM"},
|
||||
|
||||
{"%z", "-0700"},
|
||||
{"%Z", "MST"},
|
||||
|
||||
{"%N", "000000000"},
|
||||
{"%f", "000000"},
|
||||
{"%L", "000"},
|
||||
|
||||
{"%F", "2006-01-02"},
|
||||
{"%T", "15:04:05"},
|
||||
{"%R", "15:04"},
|
||||
{"%D", "01/02/06"},
|
||||
{"%r", "03:04:05 PM"},
|
||||
}
|
||||
|
||||
// StrftimeToGo converts a strftime-like layout into a Go time layout.
|
||||
func StrftimeToGo(format string) string {
|
||||
var out strings.Builder
|
||||
|
||||
for i := 0; i < len(format); {
|
||||
if format[i] != '%' {
|
||||
out.WriteByte(format[i])
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
matched := false
|
||||
for _, r := range strftimeToGoRules {
|
||||
if strings.HasPrefix(format[i:], r.strf) {
|
||||
out.WriteString(r.goLayout)
|
||||
i += len(r.strf)
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !matched {
|
||||
// Можно заменить на ошибку, если хочешь strict mode.
|
||||
out.WriteByte(format[i])
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// GoToStrftime converts a Go time layout into an approximate strftime-like layout.
|
||||
func GoToStrftime(format string) string {
|
||||
format = strings.ReplaceAll(format, "2006", "%Y")
|
||||
format = strings.ReplaceAll(format, "06", "%y")
|
||||
|
||||
format = strings.ReplaceAll(format, "15", "%H")
|
||||
format = strings.ReplaceAll(format, "03", "%I")
|
||||
format = strings.ReplaceAll(format, "3", "%-I")
|
||||
format = strings.ReplaceAll(format, "3", "%#I")
|
||||
|
||||
format = strings.ReplaceAll(format, "January", "%B")
|
||||
format = strings.ReplaceAll(format, "Jan", "%b")
|
||||
format = strings.ReplaceAll(format, "01", "%m")
|
||||
format = strings.ReplaceAll(format, "1", "%-m")
|
||||
|
||||
format = strings.ReplaceAll(format, "02", "%d")
|
||||
format = strings.ReplaceAll(format, "_2", "%e")
|
||||
format = strings.ReplaceAll(format, "2", "%-d")
|
||||
|
||||
format = strings.ReplaceAll(format, "Monday", "%A")
|
||||
format = strings.ReplaceAll(format, "Mon", "%a")
|
||||
|
||||
format = strings.ReplaceAll(format, "04", "%M")
|
||||
format = strings.ReplaceAll(format, "05", "%S")
|
||||
format = strings.ReplaceAll(format, ".999999999", "%#N")
|
||||
format = strings.ReplaceAll(format, "000000000", "%N")
|
||||
format = strings.ReplaceAll(format, ".999999", "%#f")
|
||||
format = strings.ReplaceAll(format, "000000", "%f")
|
||||
format = strings.ReplaceAll(format, ".999", "%#L")
|
||||
format = strings.ReplaceAll(format, "000", "%L")
|
||||
format = strings.ReplaceAll(format, "PM", "%p")
|
||||
|
||||
format = strings.ReplaceAll(format, "-0700", "%z")
|
||||
format = strings.ReplaceAll(format, "MST", "%Z")
|
||||
format = strings.ReplaceAll(format, "Z07:00", "%:z")
|
||||
format = strings.ReplaceAll(format, "Z07:00:00", "%::z")
|
||||
format = strings.ReplaceAll(format, "Z07", "%:::z")
|
||||
return format
|
||||
}
|
||||
+57
-33
@@ -1,60 +1,84 @@
|
||||
package slog
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func getTraceback() *MethodTraceback {
|
||||
caller, _, _, _ := runtime.Caller(5)
|
||||
details := runtime.FuncForPC(caller)
|
||||
signature := details.Name()
|
||||
path, line := details.FileLine(caller)
|
||||
splitPath := strings.Split(path, "/")
|
||||
|
||||
splitSignature := strings.Split(signature, ".")
|
||||
method := splitSignature[len(splitSignature)-1]
|
||||
|
||||
tb := &MethodTraceback{
|
||||
Filename: splitPath[len(splitPath)-1],
|
||||
FullPath: path,
|
||||
Line: line,
|
||||
Signature: signature,
|
||||
Method: method,
|
||||
}
|
||||
|
||||
return tb
|
||||
var internalTracebackMethods = map[string]struct{}{
|
||||
"Infof": {},
|
||||
"Info": {},
|
||||
"Infoln": {},
|
||||
"Warnf": {},
|
||||
"Warn": {},
|
||||
"Warnln": {},
|
||||
"Errorf": {},
|
||||
"Error": {},
|
||||
"Errorln": {},
|
||||
"Fatalf": {},
|
||||
"Fatal": {},
|
||||
"Fatalln": {},
|
||||
"Debugf": {},
|
||||
"Debug": {},
|
||||
"Debugln": {},
|
||||
"print": {},
|
||||
"println": {},
|
||||
"reportWriterError": {},
|
||||
"getTraceback": {},
|
||||
"getFullTraceback": {},
|
||||
}
|
||||
|
||||
func getTraceback() *MethodTraceback {
|
||||
tracebacks := getFullTraceback(0)
|
||||
if len(tracebacks) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tracebacks[0]
|
||||
}
|
||||
|
||||
func getFullTraceback(skip int) []*MethodTraceback {
|
||||
pc := make([]uintptr, 15)
|
||||
runtime.Callers(skip, pc)
|
||||
n := runtime.Callers(skip+2, pc)
|
||||
list := make([]*MethodTraceback, 0)
|
||||
frames := runtime.CallersFrames(pc)
|
||||
frames := runtime.CallersFrames(pc[:n])
|
||||
for {
|
||||
frame, more := frames.Next()
|
||||
tb := buildMethodTraceback(frame.PC)
|
||||
if tb != nil && !isInternalTraceback(tb) {
|
||||
list = append(list, tb)
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
details := runtime.FuncForPC(frame.PC)
|
||||
signature := details.Name()
|
||||
path, line := details.FileLine(frame.PC)
|
||||
splitPath := strings.Split(path, "/")
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func buildMethodTraceback(pc uintptr) *MethodTraceback {
|
||||
details := runtime.FuncForPC(pc)
|
||||
if details == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
signature := details.Name()
|
||||
path, line := details.FileLine(pc)
|
||||
splitPath := strings.Split(path, "/")
|
||||
splitSignature := strings.Split(signature, ".")
|
||||
method := splitSignature[len(splitSignature)-1]
|
||||
|
||||
tb := &MethodTraceback{
|
||||
return &MethodTraceback{
|
||||
Filename: splitPath[len(splitPath)-1],
|
||||
FullPath: path,
|
||||
Line: line,
|
||||
Signature: signature,
|
||||
Method: method,
|
||||
}
|
||||
list = append(list, tb)
|
||||
}
|
||||
|
||||
func isInternalTraceback(tb *MethodTraceback) bool {
|
||||
if strings.HasPrefix(tb.Signature, "runtime.") {
|
||||
return true
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool {
|
||||
return j < i
|
||||
})
|
||||
return list
|
||||
_, ok := internalTracebackMethods[tb.Method]
|
||||
return ok
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package slog
|
||||
package sneklog
|
||||
|
||||
// Map applies f to each element of s and returns the resulting slice.
|
||||
func Map[T, R any](s []T, f func(T) R) []R {
|
||||
out := make([]R, len(s))
|
||||
for i, el := range s {
|
||||
|
||||
+145
-42
@@ -1,7 +1,6 @@
|
||||
package slog
|
||||
package sneklog
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -11,67 +10,139 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// LoggerWriter is the common sink interface used by Logger.
|
||||
type LoggerWriter interface {
|
||||
Close() error
|
||||
Write(p []byte) (n int, err error)
|
||||
Print(level LogLevel, prefix string, traceback []*MethodTraceback, messages ...any) error
|
||||
}
|
||||
|
||||
// PrepareMessages normalizes message parts and extracts a trailing newline marker.
|
||||
func PrepareMessages(messages ...any) (bool, []any) {
|
||||
msg := Map(messages, func(el any) string { return fmt.Sprint(el) })
|
||||
newline := false
|
||||
if len(msg) > 0 && strings.HasSuffix(msg[len(msg)-1], "\n") {
|
||||
newline = true
|
||||
msg[len(msg)-1] = strings.TrimSuffix(msg[len(msg)-1], "\n")
|
||||
if msg[len(msg)-1] == "" {
|
||||
msg = msg[:len(msg)-1]
|
||||
}
|
||||
}
|
||||
return newline, Map(msg, func(el string) any { return any(el) })
|
||||
}
|
||||
|
||||
// LoggerTextWriter writes human-readable log records to an io.Writer.
|
||||
type LoggerTextWriter struct {
|
||||
LoggerWriter
|
||||
writer io.Writer
|
||||
printTraceback bool
|
||||
printTime bool
|
||||
closer io.Closer
|
||||
formatter *Formatter
|
||||
}
|
||||
|
||||
func (w *LoggerTextWriter) Write(p []byte) (n int, err error) {
|
||||
n, err = w.writer.Write(p)
|
||||
if err != nil {
|
||||
return n, err
|
||||
// SetFormatter replaces the formatter used by the text writer.
|
||||
func (w *LoggerTextWriter) SetFormatter(formatter *Formatter) *LoggerTextWriter {
|
||||
w.formatter = formatter
|
||||
return w
|
||||
}
|
||||
|
||||
// Formatter returns the effective formatter for the text writer.
|
||||
func (w *LoggerTextWriter) Formatter() *Formatter {
|
||||
if w.formatter == nil {
|
||||
return DefaultTextFormatter
|
||||
}
|
||||
err = bufio.NewWriter(w.writer).Flush()
|
||||
return n, err
|
||||
}
|
||||
func (w *LoggerTextWriter) Print(level LogLevel, prefix string, _ []*MethodTraceback, messages ...any) error {
|
||||
s := BuildString(level, prefix, w.printTime, w.printTraceback, messages...)
|
||||
_, err := w.Write([]byte(s))
|
||||
return err
|
||||
}
|
||||
func (w *LoggerTextWriter) Close() error {
|
||||
return w.writer.(io.Closer).Close()
|
||||
return w.formatter
|
||||
}
|
||||
|
||||
// LoggerJsonWriter write into writer JSON
|
||||
// Write forwards raw bytes to the underlying writer.
|
||||
func (w *LoggerTextWriter) Write(p []byte) (n int, err error) {
|
||||
return w.writer.Write(p)
|
||||
}
|
||||
|
||||
// Print formats the provided record as text and writes it to the underlying writer.
|
||||
func (w *LoggerTextWriter) Print(level LogLevel, prefix string, traceback []*MethodTraceback, messages ...any) error {
|
||||
newline, messages := PrepareMessages(messages...)
|
||||
|
||||
f := w.Formatter()
|
||||
s := f.FormatMessage(level, prefix, traceback, messages...)
|
||||
if f.ColorOutput && (!f.ColorOnlyStdout || w.writer == os.Stdout || w.writer == os.Stderr) {
|
||||
s = f.ColorizeString(s, level)
|
||||
}
|
||||
|
||||
_, err := w.Write([]byte(s))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if newline {
|
||||
_, err = w.Write([]byte("\n"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the owned writer, if any.
|
||||
func (w *LoggerTextWriter) Close() error {
|
||||
if w.closer == nil {
|
||||
return nil
|
||||
}
|
||||
return w.closer.Close()
|
||||
}
|
||||
|
||||
// LoggerJsonWriter writes structured log records as JSON.
|
||||
type LoggerJsonWriter struct {
|
||||
LoggerWriter
|
||||
writer io.Writer
|
||||
closer io.Closer
|
||||
pretty bool
|
||||
|
||||
formatter *Formatter
|
||||
}
|
||||
|
||||
// Formatter returns the effective formatter for the JSON writer.
|
||||
func (w *LoggerJsonWriter) Formatter() *Formatter {
|
||||
if w.formatter == nil {
|
||||
return DefaultJsonFormatter
|
||||
}
|
||||
return w.formatter
|
||||
}
|
||||
|
||||
// SetFormatter replaces the formatter used by the JSON writer.
|
||||
func (w *LoggerJsonWriter) SetFormatter(f *Formatter) *LoggerJsonWriter {
|
||||
w.formatter = f
|
||||
return w
|
||||
}
|
||||
|
||||
// LoggerJsonMessage is the JSON payload emitted by LoggerJsonWriter.
|
||||
type LoggerJsonMessage struct {
|
||||
Time time.Time `json:"time"`
|
||||
Time string `json:"time"`
|
||||
Level string `json:"level"`
|
||||
Prefix string `json:"prefix"`
|
||||
Message string `json:"message"`
|
||||
|
||||
Traceback []*MethodTraceback `json:"traceback"`
|
||||
}
|
||||
|
||||
// Write forwards raw bytes to the underlying writer.
|
||||
func (w *LoggerJsonWriter) Write(data []byte) (int, error) {
|
||||
n, err := w.writer.Write(data)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
err = bufio.NewWriter(w.writer).Flush()
|
||||
return n, err
|
||||
return w.writer.Write(data)
|
||||
}
|
||||
|
||||
// Print encodes the provided record as JSON and writes it to the underlying writer.
|
||||
func (w *LoggerJsonWriter) Print(level LogLevel, prefix string, traceback []*MethodTraceback, messages ...any) error {
|
||||
msg := Map(messages, func(el any) string {
|
||||
return fmt.Sprintf("%v", el)
|
||||
})
|
||||
newline, messages := PrepareMessages(messages...)
|
||||
|
||||
f := w.Formatter()
|
||||
s := f.FormatMessage(level, prefix, traceback, messages...)
|
||||
if f.ColorOutput && (!f.ColorOnlyStdout || w.writer == os.Stdout || w.writer == os.Stderr) {
|
||||
s = f.ColorizeString(s, level)
|
||||
}
|
||||
|
||||
m := LoggerJsonMessage{
|
||||
Time: time.Now(),
|
||||
Time: f.FormatTime(time.Now()),
|
||||
Level: level.GetName(),
|
||||
Prefix: prefix,
|
||||
Message: strings.Join(msg, " "),
|
||||
Message: s,
|
||||
Traceback: traceback,
|
||||
}
|
||||
var data []byte
|
||||
@@ -84,20 +155,33 @@ func (w *LoggerJsonWriter) Print(level LogLevel, prefix string, traceback []*Met
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write(append(data, []byte("\n")...))
|
||||
if newline {
|
||||
data = append(data, '\n')
|
||||
}
|
||||
_, err = w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
// Close closes the owned writer, if any.
|
||||
func (w *LoggerJsonWriter) Close() error {
|
||||
return w.writer.(io.Closer).Close()
|
||||
if w.closer == nil {
|
||||
return nil
|
||||
}
|
||||
return w.closer.Close()
|
||||
}
|
||||
|
||||
func CreateTextWriter(w io.Writer, printTraceback, printTime bool) *LoggerTextWriter {
|
||||
// CreateTextWriter wraps an external writer for text output without taking
|
||||
// ownership of it.
|
||||
func CreateTextWriter(w io.Writer) *LoggerTextWriter {
|
||||
writer := &LoggerTextWriter{
|
||||
writer: w, printTraceback: printTraceback, printTime: printTime,
|
||||
writer: w,
|
||||
}
|
||||
return writer
|
||||
}
|
||||
func CreateTextFileWriter(path string, printTraceback, printTime bool) (*LoggerTextWriter, error) {
|
||||
|
||||
// CreateTextFileWriter creates a text writer for path, creating parent
|
||||
// directories as needed. The returned writer owns the opened file.
|
||||
func CreateTextFileWriter(path string) (*LoggerTextWriter, error) {
|
||||
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -106,21 +190,38 @@ func CreateTextFileWriter(path string, printTraceback, printTime bool) (*LoggerT
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateTextWriter(file, printTraceback, printTime), nil
|
||||
}
|
||||
func CreateTextStdoutWriter(printTraceback, printTime bool) *LoggerTextWriter {
|
||||
return CreateTextWriter(os.Stdout, printTraceback, printTime)
|
||||
writer := CreateTextWriter(file)
|
||||
writer.closer = file
|
||||
return writer, nil
|
||||
}
|
||||
|
||||
// CreateTextStdoutWriter creates a text writer for os.Stdout without taking
|
||||
// ownership of stdout.
|
||||
func CreateTextStdoutWriter() *LoggerTextWriter {
|
||||
writer := CreateTextWriter(os.Stdout)
|
||||
writer.closer = nil
|
||||
return writer
|
||||
}
|
||||
|
||||
// CreateJsonWriter wraps an external writer for JSON output without taking
|
||||
// ownership of it.
|
||||
func CreateJsonWriter(w io.Writer, pretty bool) *LoggerJsonWriter {
|
||||
writer := &LoggerJsonWriter{
|
||||
writer: w, pretty: pretty,
|
||||
}
|
||||
return writer
|
||||
}
|
||||
|
||||
// CreateJsonStdoutWriter creates a JSON writer for os.Stdout without taking
|
||||
// ownership of stdout.
|
||||
func CreateJsonStdoutWriter(pretty bool) *LoggerJsonWriter {
|
||||
return CreateJsonWriter(os.Stdout, pretty)
|
||||
writer := CreateJsonWriter(os.Stdout, pretty)
|
||||
writer.closer = nil
|
||||
return writer
|
||||
}
|
||||
|
||||
// CreateJsonFileWriter creates a JSON writer for path, creating parent
|
||||
// directories as needed. The returned writer owns the opened file.
|
||||
func CreateJsonFileWriter(path string, pretty bool) (*LoggerJsonWriter, error) {
|
||||
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
|
||||
if err != nil {
|
||||
@@ -130,5 +231,7 @@ func CreateJsonFileWriter(path string, pretty bool) (*LoggerJsonWriter, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return CreateJsonWriter(file, pretty), nil
|
||||
writer := CreateJsonWriter(file, pretty)
|
||||
writer.closer = file
|
||||
return writer, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user