Skip to content

Commit

Permalink
(feat) support both ignore and match patterns throughout
Browse files Browse the repository at this point in the history
  • Loading branch information
kevincobain2000 committed Jun 21, 2024
1 parent afd3bb3 commit 4c4a53e
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 78 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ gol -d="container-id" \
- **v1.0.6** - UI shows grouped output.
- **v1.0.7** - Support docker logs.
- **v1.0.14** - Sleak UI changes and support dates.
- **v1.0.17** - Support both ignore and include patterns.

## Limitations

Expand Down
7 changes: 4 additions & 3 deletions frontend/src/components/Viewer.astro
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ const baseURL = import.meta.env.PUBLIC_BASE_URL;
baseURL = baseURL.replace(/\/$/, "");
let input = Alpine.reactive({
query: "",
ignore: "",
file_path: "",
realtime: false,
reverse: true,
host: "",
type: "",
page: 1,
per_page: 15,
per_page: 100,
});
let highlighter = Alpine.reactive({
line_from: 0,
Expand Down Expand Up @@ -102,7 +103,7 @@ const baseURL = import.meta.env.PUBLIC_BASE_URL;
loading.errorJSON = "";
loading.fetching = true;

const url = `${baseURL}/api?query=${input.query}&page=${input.page}&per_page=${input.per_page}&file_path=${input.file_path}&host=${input.host}&type=${input.type}&reverse=${input.reverse}`;
const url = `${baseURL}/api?query=${input.query}&ignore=${input.ignore}&page=${input.page}&per_page=${input.per_page}&file_path=${input.file_path}&host=${input.host}&type=${input.type}&reverse=${input.reverse}`;

const response = await fetch(url).catch((error) => {
loading.fetching = false;
Expand Down Expand Up @@ -151,7 +152,7 @@ const baseURL = import.meta.env.PUBLIC_BASE_URL;
clearInterval(intervalId);
}
if (input.realtime) {
intervalId = setInterval(init, 3 * 1000); // 3 seconds
intervalId = setInterval(init, 5 * 1000); // 5 seconds
}
};

Expand Down
85 changes: 36 additions & 49 deletions frontend/src/components/partials/viewer/Inputs.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,20 @@
---

<div class="mx-auto mt-10">
<div class="relative">
<div
class="absolute pt-2.5 start-0 flex items-center ps-3 pointer-events-none text-md font-bold"
>
REGEX
</div>
<input
type="text"
x-model="input.query"
@keyup="submit"
class="block font-mono w-full pl-22 p-3 ps-20 text-sm text-slate-300 hover:text-slate-100 border border-gray-300 hover:border-gray-100 rounded-lg bg-gray-900 focus:outline-none"
placeholder=".*"
required
/>
<template x-if="!loading.fetching">
<div class="grid grid-cols-2 gap-4">
<div class="relative">
<div
class="absolute pt-2.5 start-0 flex items-center ps-3 pointer-events-none text-md text-green-600"
>
MATCH REGEX
</div>
<input
type="text"
x-model="input.query"
@keyup="submit"
class="block font-mono w-full pl-36 p-3 ps-20 text-sm text-slate-300 hover:text-slate-200 border border-gray-600 hover:border-green-500 focus:border-green-500 rounded-lg bg-gray-900 focus:outline-none"
placeholder=".*"
/>
<span
class="absolute end-0.5 bottom-1.5 text-slate-300 text-sm px-4 py-0"
>
Expand All @@ -35,32 +34,21 @@
<span class="ms-3 text-sm font-bold text-gray-400">Realtime</span>
</label>
</span>
</template>
<template x-if="loading.fetching">
<button
x-bind:disabled="loading.fetching"
type="button"
@click="submit"
class="text-white disabled:text-slate-400 absolute end-2.5 bottom-1.5 bg-blue-700 disabled:bg-gray-800 hover:bg-blue-800 focus:outline-none font-bold rounded-lg text-sm px-4 py-2"
</div>
<div class="relative">
<div
class="absolute pt-2.5 start-0 flex items-center ps-3 pointer-events-none text-md text-rose-800"
>
<svg
aria-hidden="true"
role="status"
class="inline w-4 h-4 me-3 text-white animate-spin"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="#E5E7EB"></path>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentColor"></path>
</svg>
<span>Updating</span>
</button>
</template>
IGNORE REGEX
</div>
<input
type="text"
x-model="input.ignore"
@keyup="submit"
class="block font-mono w-full pl-36 p-3 ps-20 text-sm text-slate-300 hover:text-slate-100 border border-gray-600 hover:border-rose-500 focus:border-rose-500 rounded-lg bg-gray-900 focus:outline-none"
placeholder=""
/>
</div>
</div>
<template x-if="loading.error">
<span x-text="loading.error" class="text-rose-400 text-sm block mt-5"
Expand All @@ -81,9 +69,9 @@
<template
x-if="results.file_paths.filter((fp) => fp.type == type).length"
>
<div class="relative">
<div class="relative ml-1">
<div
class="absolute inset-y-0 rtl:inset-r-0 start-0 flex items-center ps-3 pointer-events-none"
class="absolute inset-y-0 rtl:inset-r-0 start-0 flex items-center ps-0 pointer-events-none"
>
<template x-if="type === 'file'">
<svg
Expand Down Expand Up @@ -164,16 +152,16 @@
</div>

<span
class="relative inline-flex items-center pl-5 pr-12 ms-5 px-0.5 py-0.5 text-sm font-medium text-center text-white border-gray-700 border-t-2 border-b-2 border-r-2"
class="relative inline-flex items-center pl-2 pr-2 ms-5 text-sm font-medium"
>
<span
class="text-sm text-gray-200 uppercase font-bold"
x-text="type"></span>
<div
class="absolute inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-gray-200 bg-blue-500 rounded-full -top-2 -end-2 dark:border-gray-900"
<span
class="pl-2 text-slate-600"
x-text="results.file_paths.filter((fp) => fp.type == type).length"
>
</div>
</span>
</span>
</div>
</template>
Expand All @@ -189,7 +177,6 @@
class="flex items-center ps-2 m-1 rounded hover:bg-gray-800"
:class="{'bg-gray-800 border-gray-900': filepath.file_path === results.result.file_path}"
>

<label
:class="{'text-blue-400': filepath.file_path === results.result.file_path, 'text-slate-400': filepath.file_path !== results.result.file_path}"
class="w-full py-2 ms-2 text-sm font-mono rounded flex items-center"
Expand Down Expand Up @@ -222,11 +209,11 @@
</template>
<span
x-show="filepath.host"
class="text-xs font-medium me-2 px-2.5 py-0.5 text-center rounded bg-yellow-700 text-gray-900"
class="text-xs font-medium me-2 px-2.5 py-0.5 text-center rounded border border-yellow-700 text-slate-300"
x-text="filepath.host"></span>
<span
x-show="filepath.name"
class="text-xs font-medium me-2 px-2.5 py-0.5 text-center rounded bg-gray-700 text-gray-300 truncate"
class="text-xs font-medium truncate"
x-text="filepath.name"></span>
<span
x-show="!filepath.file_path.startsWith('/tmp/GOL-')"
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/partials/viewer/Table.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
---

<div class="grid grid-cols-2 gap-4">
<div class="grid grid-cols-2 gap-4 mt-10">
<div class="text-left">
<label class="inline-flex items-center cursor-pointer mt-4">
<span class="mr-2 text-xs font-medium text-gray-400">Per page:</span>
Expand All @@ -26,9 +26,9 @@
</div>

<div>
<div class="overflow-x-auto mt-5 rounded">
<table class="w-full text-sm font-mono text-left text-gray-400">
<thead class="text-xs bg-gray-700 text-gray-400">
<div class="overflow-x-auto mt-5 rounded shadow-2xl">
<table class="w-full text-sm font-mono text-left text-gray-400 border border-gray-900">
<thead class="text-xs bg-gray-900 text-gray-400">
<tr>
<th scope="col" class="px-3 py-3 uppercase" style="width: 100px;">
<template x-if="input.reverse">
Expand Down Expand Up @@ -164,7 +164,7 @@
<style>
@keyframes highlight {
from {
@apply opacity-50;
@apply opacity-10;
}
to {
background-color: transparent;
Expand Down
9 changes: 5 additions & 4 deletions pkg/api_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func NewAPIHandler() *APIHandler {

type APIRequest struct {
Query string `json:"query" query:"query"`
Ignore string `json:"ignore" query:"ignore"`
FilePath string `json:"file_path" query:"file_path"`
Host string `json:"host" query:"host"`
Type string `json:"type" query:"type"`
Expand Down Expand Up @@ -77,7 +78,7 @@ func (h *APIHandler) Get(c echo.Context) error {
var watcher *Watcher
if req.Type == TypeDocker {
if !strings.HasPrefix(req.FilePath, TmpContainerPath) {
result, err := ContainerLogsFromFile(req.Host, req.Query, req.FilePath, req.Page, req.PerPage, req.Reverse)
result, err := ContainerLogsFromFile(req.Host, req.Query, req.Ignore, req.FilePath, req.Page, req.PerPage, req.Reverse)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
Expand All @@ -88,7 +89,7 @@ func (h *APIHandler) Get(c echo.Context) error {
})
}

watcher, err = NewWatcher(req.FilePath, req.Query, false, "", "", "", "", "")
watcher, err = NewWatcher(req.FilePath, req.Query, req.Ignore, false, "", "", "", "", "")
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
Expand All @@ -99,13 +100,13 @@ func (h *APIHandler) Get(c echo.Context) error {
if sshConfig == nil {
return echo.NewHTTPError(http.StatusNotFound, "ssh config not found")
}
watcher, err = NewWatcher(req.FilePath, req.Query, true, sshConfig.Host, sshConfig.Port, sshConfig.User, sshConfig.Password, sshConfig.PrivateKeyPath)
watcher, err = NewWatcher(req.FilePath, req.Query, req.Ignore, true, sshConfig.Host, sshConfig.Port, sshConfig.User, sshConfig.Password, sshConfig.PrivateKeyPath)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
}
if req.Type == TypeFile || req.Type == TypeStdin {
watcher, err = NewWatcher(req.FilePath, req.Query, false, "", "", "", "", "")
watcher, err = NewWatcher(req.FilePath, req.Query, req.Ignore, false, "", "", "", "", "")
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
Expand Down
14 changes: 13 additions & 1 deletion pkg/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func ContainerStdoutToTmp(containerID string) *os.File {
}

// ContainerLogsFromFile retrieves logs from a file within a container, processes them, and returns a ScanResult
func ContainerLogsFromFile(containerID string, query string, filePath string, page, pageSize int, reverse bool) (*ScanResult, error) {
func ContainerLogsFromFile(containerID string, query string, ignorePattern string, filePath string, page, pageSize int, reverse bool) (*ScanResult, error) {
lines := []LineResult{}
// Create a new Docker client
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
Expand All @@ -100,6 +100,15 @@ func ContainerLogsFromFile(containerID string, query string, filePath string, pa
return nil, fmt.Errorf("invalid regex pattern: %w", err)
}

// Compile the ignore regex pattern
var reIgnore *regexp.Regexp
if ignorePattern != "" {
reIgnore, err = regexp.Compile(ignorePattern)
if err != nil {
return nil, fmt.Errorf("invalid ignore regex pattern: %w", err)
}
}

// Execute a command to count the total number of lines in the file
countCmd := []string{"sh", "-c", fmt.Sprintf("wc -l < %s", filePath)}
countExecConfig := container.ExecOptions{
Expand Down Expand Up @@ -166,6 +175,9 @@ func ContainerLogsFromFile(containerID string, query string, filePath string, pa
for scanner.Scan() {
lineContent := stripansi.Strip(scanner.Text())
lineContent = CleanString(lineContent)
if reIgnore != nil && reIgnore.MatchString(lineContent) {
continue
}
if re.MatchString(lineContent) {
// Here, you might want to include logic to determine the 'Level' in the log line
lineResult := LineResult{
Expand Down
38 changes: 26 additions & 12 deletions pkg/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,20 @@ import (
)

type Watcher struct {
filePath string
matchPattern string
mutex sync.Mutex
sshConfig *ssh.ClientConfig
sshHost string
sshPort string
isRemote bool
filePath string
matchPattern string
ignorePattern string
mutex sync.Mutex
sshConfig *ssh.ClientConfig
sshHost string
sshPort string
isRemote bool
}

func NewWatcher(
filePath string,
matchPattern string,
ignorePattern string,
isRemote bool,
sshHost string,
sshPort string,
Expand All @@ -51,11 +53,12 @@ func NewWatcher(
}

watcher := &Watcher{
filePath: filePath,
matchPattern: matchPattern,
isRemote: isRemote,
sshHost: sshHost,
sshPort: sshPort,
filePath: filePath,
matchPattern: matchPattern,
ignorePattern: ignorePattern,
isRemote: isRemote,
sshHost: sshHost,
sshPort: sshPort,
sshConfig: &ssh.ClientConfig{
User: sshUser,
Auth: []ssh.AuthMethod{
Expand Down Expand Up @@ -184,6 +187,14 @@ func (w *Watcher) collectMatchingLines(scanner *bufio.Scanner) ([]LineResult, in
return nil, 0, tracerr.New(err.Error())
}

var reIgnore *regexp.Regexp
if w.ignorePattern != "" {
reIgnore, err = regexp.Compile(w.ignorePattern)
if err != nil {
return nil, 0, tracerr.New(err.Error())
}
}

var allLines []LineResult
lineNumber := 0
counts := 0
Expand All @@ -192,6 +203,9 @@ func (w *Watcher) collectMatchingLines(scanner *bufio.Scanner) ([]LineResult, in
line := scanner.Text()
line = stripansi.Strip(line)
lineNumber++
if reIgnore != nil && reIgnore.MatchString(line) {
continue
}
if re.MatchString(line) {
allLines = append(allLines, LineResult{
LineNumber: lineNumber,
Expand Down
8 changes: 4 additions & 4 deletions pkg/watcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

// TestNewWatcher tests the NewWatcher function
func TestNewWatcher(t *testing.T) {
watcher, err := NewWatcher("testfile.log", "ERROR", false, "", "", "", "", "")
watcher, err := NewWatcher("testfile.log", "ERROR", "", false, "", "", "", "", "")
assert.NoError(t, err)
assert.NotNil(t, watcher)
assert.Equal(t, "testfile.log", watcher.filePath)
Expand All @@ -33,7 +33,7 @@ ERROR Another error occurred`
assert.NoError(t, err)

// Create the Watcher
watcher, err := NewWatcher(logFile, "ERROR", false, "", "", "", "", "")
watcher, err := NewWatcher(logFile, "ERROR", "", false, "", "", "", "", "")
assert.NoError(t, err)

// Run the Scan method
Expand Down Expand Up @@ -63,7 +63,7 @@ func TestWatcher_InitializeScanner(t *testing.T) {
assert.NoError(t, err)

// Create the Watcher
watcher, err := NewWatcher(logFile, "ERROR", false, "", "", "", "", "")
watcher, err := NewWatcher(logFile, "ERROR", "", false, "", "", "", "", "")
assert.NoError(t, err)

// Initialize the scanner
Expand Down Expand Up @@ -96,7 +96,7 @@ ERROR Another error occurred`
assert.NoError(t, err)

// Create the Watcher
watcher, err := NewWatcher(logFile, "ERROR", false, "", "", "", "", "")
watcher, err := NewWatcher(logFile, "ERROR", "", false, "", "", "", "", "")
assert.NoError(t, err)

// Initialize the scanner
Expand Down

0 comments on commit 4c4a53e

Please sign in to comment.