WordPress admin-ajax.php 400 error generated by Event Tickets plugin ... database related? - ajax

I have a WordPress website for a client that uses a custom theme and a number of plugins in combination to create an events calendar where logged in users can purchase tickets for paid events and register for free RSVP-required events. To accomplish this, I am using the following six plugins in combination:
The Events Calendar
Events Calendar Pro
Event Tickets
Event Tickets Plus
WooCommerce
WooCommerce Stripe Gateway
The website was established in 2015. In the last 4 years, those plugins have seen extensive updates, and as a result, at a certain point the custom site I built around those plugins started experiencing deprecation issues, and attempts to upgrade caused performance failure. After consulting with support, it became necessary to pull a duplicate copy of the site onto a development server so that I could do the work to upgrade the install so all the latest versions of all of these plugins can be running and working properly.
Everything was going well with the upgrade work until I noticed that one of the plugins seems to be generating the following error in the console in Chrome:
POST https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php 400 (Bad Request)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
n.<computed> # jquery.js?ver=1.12.4-wp:4
r.length.e.checkAvailability # frontend-ticket-form.min.js?ver=4.11.1:1
r.length.e.init # frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) # frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) # frontend-ticket-form.min.js?ver=4.11.1:1
Loading the same page in Edge generated the following console error:
HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax
(XHR)POST - https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php
The error occurs only under very specific circumstances -- when a single event page displays the frontend form for a paid ticket. The error doesn't occur when the front end paid ticket form is not output, for example when there is a registered RSVP form with no payment component, when there is no ticket component to the event, or when a user who is not an active member views an affected page such that all information about details of the event and buying tickets is excluded from the output via theme template files. Despite the console error generated, it appears that ajax works fine and all of the functionality works exactly as expected. If you weren't looking at the console, you'd never know there was a problem.
In order to rule out an issue with my custom theme or a conflict with another plugin, I activated the default Twenty Twenty theme and deactivated all other plugins except the 6 I listed that are required to use ticketed event process. The error remained present under these circumstances
After going back and forth with Modern Tribe (the plugin developers) support desk, they report the error cannot be replicated. So I tried myself to install a clean copy of WordPress with a new database, then install only those 6 plugins while running the default Twenty Twenty theme. I did this on the same server under the same cPanel account as the dev site with the error, just at different subdomains. On the clean install, the error was NOT present. But when I then pointed the clean WordPress install to a duplicate copy of the database I'm using for the dev site I'm working on, the error shows up again. From that, I can only conclude there is something going on in my database that is making this error happen, but Modern Tribe support are telling me that since the error can't be reproduced by them, there isn't anything they can do to help.
Starting over with a clean install for this site isn't really an option, there is so much data collected over the last 4 years from ticket purchase and membership transactions that we really can't lose. I need to find the faulty data and clean it, but I feel out of my depth here. Any help or suggestions on how to resolve this are welcome.
Edited to add:
I found this code in the javascript file references by the error message in the console. Am I looking in the right place?
/**
* Check tickets availability.
*
* #since 4.9
*
* #return void
*/
obj.checkAvailability = function() {
// We're checking availability for all the tickets at once.
var params = {
action : 'ticket_availability_check',
tickets : obj.getTickets(),
};
$.post(
TribeTicketOptions.ajaxurl,
params,
function( response ) {
var success = response.success;
// Bail if we don't get a successful response.
if ( ! success ) {
return;
}
// Get the tickets response with availability.
var tickets = response.data.tickets;
// Make DOM updates.
obj.updateAvailability( tickets );
}
);
// Repeat every 60 (filterable via tribe_tickets_availability_check_interval ) seconds
if ( 0 < TribeTicketOptions.availability_check_interval ) {
setTimeout( obj.checkAvailability, TribeTicketOptions.availability_check_interval );
}
}
Edited to add:
Then I ran a string search for ticket_availability and found the following. It looks like it might be related, but I'm a bit over my head in interpreting. Am I on the right track yet?
public function ticket_availability( $tickets = array() ) {
$response = array( 'html' => '' );
$tickets = tribe_get_request_var( 'tickets', array() );
// Bail if we receive no tickets
if ( empty( $tickets ) ) {
wp_send_json_error( $response );
}
/** #var Tribe__Tickets__Tickets_Handler $tickets_handler */
$tickets_handler = tribe( 'tickets.handler' );
/** #var Tribe__Tickets__Editor__Template $tickets_editor */
$tickets_editor = tribe( 'tickets.editor.template' );
// Parse the tickets and create the array for the response
foreach ( $tickets as $ticket_id ) {
$ticket = Tribe__Tickets__Tickets::load_ticket_object( $ticket_id );
if (
! $ticket instanceof Tribe__Tickets__Ticket_Object
|| empty( $ticket->ID )
) {
continue;
}
$available = $tickets_handler->get_ticket_max_purchase( $ticket->ID );
$response['tickets'][ $ticket_id ]['available'] = $available;
// If there are no more available we will send the template part HTML to update the DOM
if ( 0 === $available ) {
$response['tickets'][ $ticket_id ]['unavailable_html'] = $tickets_editor->template( 'blocks/tickets/quantity-unavailable', $ticket, false );
}
}
wp_send_json_success( $response );
}
The weird thing is that this function is filed to a folder called Blocks, which implied it works with Gutenberg, which I have disabled via the Classic Editor plugin.

StackOverflow powers that be, forgive me but this was too much to fit in a comment.
I apologize, but this is more of a debug process than a strict answer.
The admin-ajax.php file only has 3 scenarios to return a 400 error.
If the user is logged in, and the ajax function hasn't been added to the wp_ajax_{function_name} action. (line #164)
The user is NOT logged in, and the ajax function hasn't been added to the wp_ajax_nopriv_{function_name} action. (line #179)
No action was sent in the request. (line #32)
You'll need to figure out which of these is causing your error. If you're not sure how to do this, an easy way is to temporarily edit your admin-ajax.php file. Before you see this:
// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
Add in the following (again, before the above lines)
ob_start();
print( '<pre>'. print_r($_REQUEST, true) .'</pre>' );
wp_mail( 'your-email#address.com', 'Debug Results', ob_get_clean() );
This will email you (semi-nicely) formatted dump of the $_REQUEST. If there's no action, you'll know that for some reason the "front end form for a paid ticket" function isn't being added, and Modern Tribe could probably help you out with that.
If the action is set, you can add a similar line down below at line 164 or 179 and repeat the above, but with print( '<pre>'. print_r($action, true) .'</pre>' ); instead. If either of these get emailed to you when you submit the form, you'll know which ajax hook isn't being added, and again Modern Tribe could probably help you from there.
Also note, that modifying core WP files is generally bad practice and you should revert these changes when you're done debugging. (There's ways to hook into file instead, but for ease/speed of diagnostics, go ahead and temporarily edit it, as these aren't permanent changes, and it's on a development site, so you shouldn't have to worry)
Beyond the above, you'll probably need to hire a developer look at it, there's not much more that someone on Stack Overflow can do without having direct access to your database and files.

I am having the same problem and I think the problem is Tribe__Editor::should_load_blocks when the classic editor plugin is active.
To bypass this error I add this code to my theme functions.php file
add_action( 'xxx', tribe_callback( 'tickets.editor.blocks.tickets', 'register' ) );
do_action( 'xxx' );
I hope this works for you.

The advice I received from the plugin developers after a great deal of back and forth was to add the following to my theme's functions.php file:
add_filter( 'tribe_tickets_availability_check_interval', function( $interval) {
return 0;
} );
This resolves the console issue, does not generate additional errors, and does not interfere with any expected functionality in all tests performed thus far.

Wanted to update everyone that with the release of Event Tickets 4.11.4 and Event Tickets Plus 4.11.3, this issue has been completely resolved on the plugin side. So apparently this was not just an issue with my site only. Thank you to everyone who contributed.

Related

Workbox cache group is not correct

I'm using workbox-webpack-plugin v5 (the latest) with InjectManifest plugin. The following is my service worker source file:
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { clientsClaim, setCacheNameDetails, skipWaiting } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import {
cleanupOutdatedCaches,
createHandlerBoundToURL,
precacheAndRoute,
} from 'workbox-precaching';
import { NavigationRoute, registerRoute, setCatchHandler } from 'workbox-routing';
import { CacheFirst, NetworkOnly, StaleWhileRevalidate } from 'workbox-strategies';
setCacheNameDetails({
precache: 'install-time',
prefix: 'app-precache',
runtime: 'run-time',
suffix: 'v1',
});
cleanupOutdatedCaches();
clientsClaim();
skipWaiting();
precacheAndRoute(self.__WB_MANIFEST);
precacheAndRoute([{ url: '/app-shell.html', revision: 'html-cache-1' }], {
cleanUrls: false,
});
const handler = createHandlerBoundToURL('/app-shell.html');
const navigationRoute = new NavigationRoute(handler);
registerRoute(navigationRoute);
registerRoute(
/.*\.css/,
new CacheFirst({
cacheName: 'css-cache-v1',
})
);
registerRoute(
/^https:\/\/fonts\.(?:googleapis|gstatic)\.com/,
new CacheFirst({
cacheName: 'google-fonts-cache-v1',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30,
}),
],
})
);
registerRoute(
/.*\.js/,
new StaleWhileRevalidate({
cacheName: 'js-cache-v1',
})
);
setCatchHandler(new NetworkOnly());
I have the following questions/problems:
Cache group is not correct. Everything except google fonts is under workbox-precache-v2 or app-precache-install-time-v1 cache group, not individual cache groups such as css-cache-v1, js-cache-v1. However, 1 in 20 times, it shows correct cache group, and I just can't figure out why.
Google font shows from memory cache. Is it correct? It works fine in offline, but what will happen if the user closes the browser/machine and comes back in offline mode?
Is '/app-shell.html' usage correct? It's an express backend app with * as the wild card for all routes, and React Router handles the routing. Functionally, it's working fine offline. I don't have any app-shell.html page.
Thanks for your help.
Cache group is not correct. Everything except google fonts is under workbox-precache-v2 or app-precache-install-time-v1 cache group, not individual cache groups such as css-cache-v1, js-cache-v1. However, 1 in 20 times, it shows correct cache group, and I just can't figure out why.
It depends on what's in your precache manifest (i.e. what self.__WB_MANIFEST gets replaced with during your webpack build).
For example, let's say you have a file generated by webpack called bundle.js, and that file ends up in your precache manifest. Based on your service worker code, that file will end up in a cached called app-precache-install-time-v1—even though it also matches your runtime route with the cache js-cache-v1.
The reason is because your precache route is registered before you runtime route, so your precaching logic will handle that request rather than your runtime caching logic.
Google font shows from memory cache. Is it correct? It works fine in offline, but what will happen if the user closes the browser/machine and comes back in offline mode?
I believe this means the request is not being handled by the service worker, but you can check the workbox logs in the developer console to verify (and see why not).
Alternatively, you could update your code to use a custom handler that just logs whether it's running like so:
registerRoute(
/^https:\/\/fonts\.(?:googleapis|gstatic)\.com/,
({request}) => {
// Log to make sure this function is being called...
console.log(request.url);
return fetch(request);
}
);
Is '/app-shell.html' usage correct? It's an express backend app with * as the wild card for all routes, and React Router handles the routing. Functionally, it's working fine offline. I don't have any app-shell.html page.
Does your express route respond with a file called app-shell.html? If so, then you'd probably want your precache revision to be a hash of the file itself (rather than revision: 'html-cache-1'). What you have right now should work, but the risk is you'll change the contents of app-shell.html, deploy a new version of your app, but your users will still see the old version because you forgot up update revision: 'html-cache-1'. In general it's best to use revisions generated as part of your build step.

Tips on solving 'DevTools was disconnected from the page' and Electron Helper dies

I've a problem with Electron where the app goes blank. i.e. It becomes a white screen. If I open the dev tools it displays the following message.
In ActivityMonitor I can see the number of Electron Helper processes drops from 3 to 2 when this happens. Plus it seems I'm not the only person to come across it. e.g.
Facing "Devtools was disconnected from the page. Once page is reloaded, Devtools will automatically reconnect."
Electron dying without any information, what now?
But I've yet to find an answer that helps. In scenarios where Electron crashes are there any good approaches to identifying the problem?
For context I'm loading an sdk into Electron. Originally I was using browserify to package it which worked fine. But I want to move to the SDKs npm release. This version seems to have introduced the problem (though the code should be the same).
A good bit of time has passed since I originally posted this question. I'll answer it myself in case my mistake can assist anyone.
I never got a "solution" to the original problem. At a much later date I switched across to the npm release of the sdk and it worked.
But before that time I'd hit this issue again. Luckily, by then, I'd added a logger that also wrote console to file. With it I noticed that a JavaScript syntax error caused the crash. e.g. Missing closing bracket, etc.
I suspect that's what caused my original problem. But the Chrome dev tools do the worst thing by blanking the console rather than preserve it when the tools crash.
Code I used to setup a logger
/*global window */
const winston = require('winston');
const prettyMs = require('pretty-ms');
/**
* Proxy the standard 'console' object and redirect it toward a logger.
*/
class Logger {
constructor() {
// Retain a reference to the original console
this.originalConsole = window.console;
this.timers = new Map([]);
// Configure a logger
this.logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new winston.transports.File(
{
filename: `${require('electron').remote.app.getPath('userData')}/logs/downloader.log`, // Note: require('electron').remote is undefined when I include it in the normal imports
handleExceptions: true, // Log unhandled exceptions
maxsize: 1048576, // 10 MB
maxFiles: 10
}
)
]
});
const _this = this;
// Switch out the console with a proxied version
window.console = new Proxy(this.originalConsole, {
// Override the console functions
get(target, property) {
// Leverage the identical logger functions
if (['debug', 'info', 'warn', 'error'].includes(property)) return (...parameters) => {
_this.logger[property](parameters);
// Simple approach to logging to console. Initially considered
// using a custom logger. But this is much easier to implement.
// Downside is that the format differs but I can live with that
_this.originalConsole[property](...parameters);
}
// The log function differs in logger so map it to info
if ('log' === property) return (...parameters) => {
_this.logger.info(parameters);
_this.originalConsole.info(...parameters);
}
// Re-implement the time and timeEnd functions
if ('time' === property) return (label) => _this.timers.set(label, window.performance.now());
if ('timeEnd' === property) return (label) => {
const now = window.performance.now();
if (!_this.timers.has(label)) {
_this.logger.warn(`console.timeEnd('${label}') called without preceding console.time('${label}')! Or console.timeEnd('${label}') has been called more than once.`)
}
const timeTaken = prettyMs(now - _this.timers.get(label));
_this.timers.delete(label);
const message = `${label} ${timeTaken}`;
_this.logger.info(message);
_this.originalConsole.info(message);
}
// Any non-overriden functions are passed to console
return target[property];
}
});
}
}
/**
* Calling this function switches the window.console for a proxied version.
* The proxy allows us to redirect the call to a logger.
*/
function switchConsoleToLogger() { new Logger(); } // eslint-disable-line no-unused-vars
Then in index.html I load this script first
<script src="js/logger.js"></script>
<script>switchConsoleToLogger()</script>
I had installed Google Chrome version 79.0.3945.130 (64 bit). My app was going to crash every time when I was in debug mode. I try all the solutions I found on the web but no one was useful. I downgrade to all the previous version:
78.x Crashed
77.x Crashed
75.x Not Crashed
I had to re-install the version 75.0.3770.80 (64 bit). Problem has been solved. It can be a new versions of Chrome problem. I sent feedback to Chrome assistence.
My problem was that I was not loading a page such as index.html. Once I loaded problem went away.
parentWindow = new BrowserWindow({
title: 'parent'
});
parentWindow.loadURL(`file://${__dirname}/index.html`);
parentWindow.webContents.openDevTools();
The trick to debugging a crash like this, is to enable logging, which is apparently disabled by default. This is done by setting the environment variable ELECTRON_ENABLE_LOGGING=1, as mentioned in this GitHub issue.
With that enabled, you should see something along the lines of this in the console:
You can download Google Chrome Canary. I was facing this problem on Google Chrome where DevTools was crashing every time on the same spot. On Chrome Canary the debugger doesn't crash.
I also faced the exact same problem
I was trying to require sqlite3 module from renderer side
which was causing a problem but once i removed the request it was working just fine
const {app , BrowserWindow , ipcMain, ipcRenderer } = require('electron')
const { event } = require('jquery')
const sqlite3 = require('sqlite3').verbose(); // <<== problem
I think the best way to solve this (if your code is really really small) just try to remove functions and run it over and over again eventually you can narrow it down to the core problem
It is a really tedious , dumb and not a smart way of doing it , but hey it worked
I encountered this issue, and couldn't figure out why the the DevTool was constantly disconnecting. So on a whim I launched Firefox Developer edition and identified the cause as an undefined variable with a string length property.
if ( args.length > 1 ) {
$( this ).find( "option" ).each(function () {
$( $( this ).attr( "s-group" ) ).hide();
});
$( args ).show();
}
TL;DR Firefox Developer edition can identify these kinds of problems when Chrome's DevTool fails.
After reading the comments above it is clear to me that there is a problem at least in Chrome that consists of not showing any indication of what the fault comes from. In Firefox, the program works but with a long delay.
But, as Shane Gannon said, the origin of the problem is certainly not in a browser but it is in the code: in my case, I had opened a while loop without adding the corresponding incremental, which made the loop infinite. As in the example below:
var a = 0;
while (a < 10) {
...
a ++ // this is the part I was missing;
}
Once this was corrected, the problem disappeared.
I found that upgrading to
react 17.0.2
react-dom 17.0.2
react-scripts 4.0.3
but also as react-scripts start is being used to run electron maybe its just react scripts that needs updating.
Well I nearly went crazy but with electron the main problem I realized I commented out the code to fetch (index.html)
// and load the index.html of the app.
mainWindow.loadFile('index.html');
check this side and make sure you have included it. without this the page will go black or wont load. so check your index.js to see if there's something to load your index.html file :) feel free to mail : profnird#gmail.com if you need additional help
Downgrade from Electron 11 to Electron 8.2 worked for me in Angular 11 - Electron - Typeorm -sqlite3 app.
It is not a solution as such, but it is an assumption of why the problem.
In the angular 'ngOnInit' lifecycle I put too many 'for' and 'while' loops, one inside the other, after cleaning the code and making it more compact, the problem disappeared, I think maybe because it didn't finish the processes within a time limit I hope someone finds this comment helpful. :)
I have stumbled upon the similar problem, My approach is comment out some line that I just added to see if it works. And if that is the case, those problem is at those lines of code.
for(var i = 0;i<objLen; i+3 ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
The console works fine after i change the code to like this.
for(var i = 0;i<objLen; i=i+space ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
Open your google dev console (Ctrl + shift + i). Then press (fn + F1) or just F1, then scroll down and click on the Restore defaults and reload.

Ajax request POST returns 403 error, GET returns 200 ok on same url

I'm trying to set up a prestashop webshop and I bought a theme to customize it. Instalation works great, but when reaching the live edit module of the theme I ran into a problem: after customizing the layout I tried to save my modifications, but it returns with 403 error. I've tried to debug it, I've contacted my hosting, I've contacted the developer of the theme, but noone can help me. In the error logs doesn't appear anything regarding this issue. The developer says it is tested on multiple hosts, and it works great. My host says they can't do anything if there is no error message in the logs.
I've managed to circle down the issue a little bit. There is a larger sized parameter(it contains all new configurations) which if I disable to be sent, then I get the following error: "Your hosting provider has set a non-standard or too little value of parameter LimitRequestLine in httpd.conf. Set the default setting value of parameter LimitRequestLine in httpd.conf, please." This error I receive on post and get aswell.
This parameter can be the source of my problem if the http call is through ajax post? Or there is more this issue?
I'm trying to solve this issue for 3 months now, I've spoken to the hosting firm, I've spoken to the developer of the them, I've searched a lot of forums but found no answer to this. I'm desperate to get any help on this matter.
It looks like I solved the issue with the following codes:
/public_html/modules/ixtengine/js/cpanel/cpanel.min.js
... ,$.ajax({type:"POST",url:cpfuncurl+previewfun,data:{ ...
replaced by
... ,$.ajax({type:"PUT",url:cpfuncurl+previewfun,data:{ ...
and
... ,$.ajax({type:"POST",url:cpfuncurl+savefun,data:{ ...
replaced by
... ,$.ajax({type:"PUT",url:cpfuncurl+savefun,data:{ ...
/public_html/modules/ixtengine/cpanel/functions/upload.savepf.php and /public_html/modules/ixtengine/cpanel/functions/upload.previewwid.php
...
$theme = Tools::getValue('theme');
$conf = Tools::getValue('conf');
$skin = Tools::getValue('skin');
$skinid = Tools::getValue('skinid');
$token = Tools::getValue('token');
...
replaced by
...
$put_vars=array();
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
parse_str(file_get_contents("php://input"),$put_vars);
$theme = $put_vars['theme'];
$conf = $put_vars['conf'];
$skin = $put_vars['skin'];
$skinid = $put_vars['skinid'];
$token = $put_vars['token'];
}
else
{
$theme = Tools::getValue('theme');
$conf = Tools::getValue('conf');
$skin = Tools::getValue('skin');
$skinid = Tools::getValue('skinid');
$token = Tools::getValue('token');
}
...
This solution is particulary for the ixtengine module for some hosts where POST returns 403 error so I can't be sure if this method will work for someone else running into this problem, but it works for me.

Drupal 7 AJAX and "CAPTCHA session reuse attack detected." in captcha-7.x-1.x-dev

I am experiencing problems with the captcha-7.x-1.x-dev version , In a form if i used any AJAX processed fields, after I submit it I receive the error CAPTCHA session reuse attack detected.. If there are no AJAX processed fields means it is working properly.
This is still an issue in the current 7.x-1.0-beta2 version of the Captcha module. However, jay.daysand put in a comment on a issue saying he created a module to fix this issue that you can download and use:
Check out the experimental fix module
http://drupal.org/sandbox/dansandj/1970786 and let me know if it
solves your problems. I can easily add support for more endpoints than
just "file/ajax", just let me know.
I downloaded this module and it works great, but had to modify the captcha_ajax_fix_captcha_element_value() method to check for FAPI ajax calls:
// If this is form is an AJAX submission to "file/ajax", don't process the
// CAPTCHA element.
if (arg(0) == 'file' && arg(1) == 'ajax' || arg(0) == 'system' && arg(1) == 'ajax') {
$element['#processed'] = TRUE;
}
This is a known issue and i was searching for a patch and i found it.
this might be useful
https://www.drupal.org/node/1395184
https://drupal.stackexchange.com/questions/27936/captcha-session-reuse-attack-detected-error-message-when-form-is-submitted

Joomla >1.7 hide log messages from browser

I'm developing an extension for Joomla!; at the moment I'm trying to make it 3.0 compatible - as with 3.0 the logging changed a little (*). Building on the answer from this related question, my current code looks like this:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php'
));
JLog::add('blah blah log msg');
The problem is that the log also goes to the messages which are shown to the user - this I want to prevent, I want the log msg only to go to the log file. I think it has to do with the "category" that JLog::add takes as a 3rd (optional) parameter, but I have no idea what to pass there?
Can anybody tell me how to hide the messages / or tell me if I'm on the right way with the categories and what value I should use?
Thanks!
(*) It actually changed already with 1.7 as far as I gathered so far, but the old method of calling addEntry on the return of JLog::getInstance(...) seems to have been removed from 2.5 to 3.0.
Edit: Think I found a way now; using:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php',
JLog::ALL,
'myplg'
));
JLog::add('blah blah log msg', JLog::INFO, 'myplg');
all my log entries go only into my log file (and not to the messages shown to the user). However, I also get a few deprecation warnings - one about my code, but also some unrelated ones:
WARNING deprecated JAccess::getActions is deprecated. Use JAccess::getActionsFromFile or JAcces::getActionsFromData instead.
WARNING deprecated JSubMenuHelper::getEntries() is deprecated. Use JHtmlSidebar::getEntries() instead.
WARNING deprecated JSubMenuHelper::getFilters() is deprecated. Use JHtmlSidebar::getFilters() instead.
WARNING deprecated JSubMenuHelper::getAction() is deprecated. Use JHtmlSidebar::getAction() instead.
Not sure what to make of those - why do they appear in my log file, shouldn't they go to the default error.log file instead of my file ?
This is what I am using, works for Joomla 1.5 - 3.2:
if(version_compare(JVERSION,'1.7.0','ge')) {
jimport('joomla.log.log'); // Include the log library (J1.7+)
$priorities = JLog::ALL ^ JLog::WARNING; // exclude warning (because of deprecated)
// In J3.0 we need to ensure that log messages only go to our file, thus use the categories (already supported in J2.5)
if(version_compare(JVERSION,'2.5.0','ge')) {
$logCategory = 'com_mycomponent';
JLog::addLogger(array('text_file' => $logFileName), $priorities, $logCategory);
JLog::add($msg, JLog::INFO, $logCategory);
}else{
JLog::addLogger(array('text_file' => $logFileName), $priorities);
JLog::add($msg, JLog::INFO);
}
} else {
// Joomla! 1.6 and 1.5
jimport('joomla.error.log'); // Include the log library
$log = &JLog::getInstance($logFileName);
$log->addEntry(array('comment' => $msg, 'level' => 'INFO'));
}
This shows the trick for gettring of the deprecated messages.
And yes, you have to include a category for your messages to ensure they are not showing up as system messages.
Use
new JException('Something happened');
This will only add it to debug log but will not show anything.
It seems, that Joomla 3.0 has no default logger enabled. The same in Joomla 3.0.3. Nothing turns logging on by default - even Debug mode.
Finally I think I have solved my issue with unrelated log entries showing up.
A close look at the API documentation of the addLogger function revealed that the third parameter, $categories, is supposed to be an array of categories for which this log will be used.
This is in contradiction to the version of http://docs.joomla.org/Using_JLog that is current at the time of this writing, where a single category is given instead of an array.
Changing my call to addLogger to use an array, like this:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php',
JLog::ALL,
array('myplg')
));
And keeping my fingers crossed that this will fix the issue!
Edit: unfortunately even this still doesn't solve my issue - still got unrelated entries :(.
I found the answer.. hope this script make you understand.. I already built as function . this code work on joomla 3. hope work in joomla 2
<?php
function logWrite($level, $values, $file='%s.php',$path='',$showOnTop=0,
$option='',$component=''){
/****
jlog Joomla 3.4
created by:gundambison (2015.04.26).
THX: hbit#stackoverflow
****/
jimport('joomla.log.log');
$level=strtoupper($level);
//You can change this com_name
$component= $component==''? 'com_gundambison': $component;
$date= date("Ymd");
$filename= sprintf($file, $date);
$format= $option=='' ?"{TIME}\t{CLIENTIP}\t{CATEGORY}\t{MESSAGE}": $option;
// create options and text
$txt = is_array($values)? json_encode($values): $values;
$options = array('text_file' => $filename,'text_entry_format'=>$format );
$options['text_file_path']=$path==''?'logs': $path;
JLog::addLogger ($options);
/*
if you want the error to show in your page. just see the different
*/
if($showOnTop==1){
JLog::add("$txt");
}
else{
JLog::add("$level\t$txt",$level,$component);
}
}

Resources